When I initialize an array a[][]
:
int a[2][5]={(8,9,7,67,11),(7,8,9,199,89)};
and then display the array elements.
Why do I get:
11 89 0 0 0
0 0 0 0 0
What happens if you use curly braces instead of the first brackets here?
(8,9,7,67,11)
is an expression using the comma operator that evaluates to 11. The same holds for the other initialiser. So you only initialise the first two elements explicitly, all others are then initialised to 0. Your compiler should warn about a missing level of braces in the initialiser.
If you use curly braces, you initialise the two component arrays of a
, as is probably intended.
int a[2][5]={(8,9,7,67,11),(7,8,9,199,89)};
is equivalent to (at block scope):
int a[2][5]={11, 89};
,
is the C comma operator. It evaluates its operands from left to right and yields the value of the right operand.
At file scope array initializers must be constant and as the ,
expression is never a constant expression, you array declaration is invalid.
Because you're not using braces, but parentheses. You want:
int a[2][5] = { { 8,9,7,67,11 }, { 7,8,9,199,89 } };
// ^^^ ^^^^^^ ^^^
In your original code, you've just made acquaintance with the comma operator, and you've actually written int a[2][5] = { 11, 89 };
. This is legal, but it initializes all missing elements to zero.
It's the concept of comma operator
and comma separator
You must have to use {}
to initialize array
int a[2][5]={(8,9,7,67,11),(7,8,9,199,89)};
here (8,9,7,67,11)
is equivalent to 11
because of comma operator
and (7,8,9,199,89)
is equivalent to 89
for the same because comma operator is evaluated to left to right
and the right most value is the value returned
hence it's equivalent to a[2][5]={11,89}
but (8,9,7,67,11),(7,8,9,199,89)
but comma used in () , ()
is comma separator