I am interested by code asked by my friend. The code is below:
1 2 3 4 5
1 int a [ 2 ] = { 1 , 2 } ;
2 int b [ 2 ] = { ( 1 , 2 ) } ;
3
4 cout << a [ 0 ] << " " << a [ 1 ] << endl ;
5 cout << b [ 1 ] << " " << b [ 1 ] << endl ;
What surprised me is that line 2 compiled successfully. This is the first time I've seen code like that. What I want to ask is, what is the meaning of using "( )" when initialising array? After some tests, I found that the last number will always be taken.
This is a funky thing that has to do with the comma operator. The parenthesis just make the comma operator function before the initializer.
The comma operator lets you combine multiple statements into one statement. Statements are performed left to right, and the right-most result is returned. IE:
1 2 3 4 5 6 7 8 9 10 11 12 13
int a = 0;
int b = 1;
a = (b += 1, b + 3);
/*
First: b += 1 is performed, b==2
Next: b + 3 is performed, yeilding 5
Last: a = 5 because the right-most operation yielded 5
end result:
b = 2
a = 5
*/
When put in an array initializer, the parenthesis tell the compiler to evaluate the comma operator first. The result of that operation (the right-most value) is what the parenthesis "outputs", which is what gets put in the array.
The trailing 0 is just because arrays are automatically filled with 0 for uninitialized elements if at least 1 element was initialized.
ie:
1 2 3 4 5
int foo[5] = { (1,2) };
is the same as
int foo[5] = { 2 };
is the same as
int foo[5] = { 2,0,0,0,0 };