1D and 2D array initialization with braces
c
Solution
In the first example:
int a[]=(1,2,3);
the initializer is a (rather odd) expression of type `int`. (It contains two comma operators, and yields the value `3`.) The object is an array. The initialization is invalid because it's a type mismatch.
The second:
int a[][2]={(1,2),(3,4)};
is equivalent to:
int a[][2] = { 2, 4 };
which is valid because it's permissible to omit nested curly braces in an initializer; elements are used to initialize successive elements of the object. The first and third commas are comma operators; the second is a delimiter.
The outermost curly braces are optional if the initializer is simply an expression of the target type, whether it's a scalar, struct, or union. For example, you can write:
int x = 42;
int y = { 42 };
The outermost curly braces are required for an initializer that specifies element values (for an array, struct, or union object).
For example:
struct foo {
int x;
int y;
};
struct foo arr[2] = { 1, 2, 3, 4 };
is valid -- but it's more clearly written as:
struct foo arr[2] = { { 1, 2 }, { 3, 4 } };
Apart from the first example being invalid, both are poor style. The first may have been intended to be:
int a[] = { 1, 2, 3 };
and the second either:
int a[][2] = { 2, 4 };
or
int a[][2] = {{1, 2}, {3, 4}};
depending on the intent.
Problem
The following code gives an "invalid initializer" error: ``` int a[]=(1,2,3); ``` But the following compiles successfully although it considers ',' as comma OPERATOR and not SEPARATOR: ``` int a[][2]={(1,2),(3,4)}; ``` So why is `()` invalid for a 1D array and not for a 2D array?