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

Explain, please.

+5
source share
1 answer

Because it ,has a lower priority than =. In fact, it ,has the lowest priority for all operators.

The first case:

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

It is equivalent

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

So, xit becomes 6 + 2 = 8, then it increases and becomes 9. The next expression is no-op, that is, the value is x-4calculated and discarded, and then it increases again, now x10, and finally another non-op. x = 10 .

Second case:

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

It is equivalent

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

x+2, x 7, x - 4, x 8, , , x+5, 13. , , . x.
x = 13.

, .

, -

,

+15

All Articles