2

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?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
S M
  • 35
  • 6

4 Answers4

8
(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.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
3
 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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Thanks for the scope point but I am not getting an error having declared the array in the file scope. Is it compiler dependent? – S M Nov 03 '12 at 17:39
  • @SauravM `gcc` for example gives an error and stops the translation. Compilers are free to extend the language and accept such a program but then the program is not strictly conforming. – ouah Nov 03 '12 at 19:33
3

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

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

Omkant
  • 9,018
  • 8
  • 39
  • 59