Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C what exactly happens if i use () to initialize a double dimension array instead of the {}?

Tags:

c

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?

like image 967
S M Avatar asked Jan 30 '26 16:01

S M


2 Answers

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

like image 151
Daniel Fischer Avatar answered Feb 02 '26 06:02

Daniel Fischer


 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.

like image 35
ouah Avatar answered Feb 02 '26 07:02

ouah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!