Why does int a[x,y] convert into a[y], since comma operator operates left to right? I would expect a[(x,y)], since inner operation will finish first. But in the first one it is supposed to take the first argument.
I'm not planning to use the comma operator for array initialization, just asking why this happens.
I read it in a book, and I'm confused.
Update:
Wikipedia says:
i = a, b, c; // stores a into i
i = (a, b, c); // stores c into i
So as first line of code says in the array the first value must be assigned to the array. Note: I'm not actually planning to use this. I'm just asking. I'm learning C++ and I read in a book that in an array declaration a[y,x]; so it should be a[y], x; not a[x]. Why does the compiler do this?
The comma operator , is also known as the "forget" operator. It does the following:
So in your case, it behaves just as it should. a[x, y] first evaluates x, then discards its value, then uses the value of y as the value of the entire expression (the one in brackets).
EDIT
Regarding your edit with Wikipedia. Note that the precedence of , is less than that of =. In other words,
i = a, b, c;
is interpreted as
(i = a), b, c;
That's why a is copied into i. However, the result of the entire expression will still be c.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With