Gautam Kumar
Gautam Kumar

Reputation: 1170

comma operators in c++

int main() {
   int x = 6;
   x = x+2, ++x, x-4, ++x, x+5;
   std::cout << x;
}

// Output: 10

int main() {
   int x = 6;
   x = (x+2, ++x, x-4, ++x, x+5);
   std::cout << x;
}

// Output: 13

Please explain.

Upvotes: 5

Views: 165

Answers (1)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

Because , has lower precedence than =. In fact, , has the lowest precedence of all operators.

First case:

x=x+2,++x,x-4,++x,x+5;

This is equivalent to

(x=x+2),(++x),(x-4),(++x),(x+5);

So, x becomes 6+2 = 8, then it is incremented and becomes 9. The next expression is a no-op, that is x-4 value is calculated and discarded, then increment again, now x is 10, and finally, another no-op. x is 10.

Second case:

x=(x+2,++x,x-4,++x,x+5);

This is equivalent to

x=((x+2),(++x),(x-4),(++x),(x+5));

x+2 is calculated, then x is incremented and becomes 7, then x - 4 is calculated, then x is incremented again and becomes 8, and finally x+5 is calculated which is 13. This operand, being the rightmost one, is the taken as the result of the whole comma expression. This value is assigned to x.
x is 13.

Hope it's clear.

And, as one of the comments suggests -

NEVER WRITE CODE LIKE THIS

Upvotes: 15

Related Questions