Reputation:
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:
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?
Upvotes: 3
Views: 125
Reputation: 171127
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
.
Upvotes: 9
Reputation: 472
I believe that your compiler is assuming that you meant to add parentheses. In C++ there's a comma operator and a comma separator. The comma operator must itself and its operands be enclosed in parentheses. The int array constructor only expects one value, so I'm guessing that your compiler is trying to help you out.
http://msdn.microsoft.com/en-us/library/zs06xbxh(v=vs.80).aspx
EDIT: int a[x,y] is not valid; int a[(x,y)] is valid; his compiler is assuming he meant to add parentheses. In a more general context the comma operator doesn't require parentheses. In function calls and initializers parentheses are required to distinguish between using a comma operator and a comma separator.
Upvotes: 0