Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do operators operate in array declarations?

Tags:

c++

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?


1 Answers

The comma operator , is also known as the "forget" operator. It does the following:

  1. Completely evaluate the left operand
  2. Forget its value
  3. Completely evaluate the right operand
  4. Use value of right operand as value of entire operator expression.

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.

like image 189
Angew is no longer proud of SO Avatar answered Apr 23 '26 00:04

Angew is no longer proud of SO



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!