Complex Comma Operators

I need help understanding this. I get the simple example given in the tutorial, but im confused on the bit more complex examples, like the following:

1
2
3
int a,b=7;
a = (b+3, b-2, b++);
cout << a << "\t" << b;


It gives an output of: 7 ------ 8

Why? I was expecting both a and b to be 8.

Also, if I change b++ to simple b+1, it gives an output of: 8 ------ 7

Again, confused on why that is. I again expected both to be 8.

Help me understand this please?

And can people share more creative/complex examples which may help me understand this better?

Last edited on
The comma operator evaluates the left operand and discards it.

a = (b+3, b-2, b++); is the same as
a = ((b+3, b-2), b++);

If we then apply the rule, we evaluate the left operand (b+3, b-2) which has no side effects, and then we discard the result leaving us with:

a = b++;

We know that b is 7. The post increment operator is used on b, so the value of the expression b++ is 7. This is what is assigned to a. The side effect of the expression b++ is that b is incremented by 1, so b is 8.

Last edited on
That clarifies it a little. I forgot that the post-increment doesn't change the value of b until AFTER the assignment statement.

So just to make this clear: No matter how many expressions I put in those parenthesis, only the very last one will be assigned to a, correct?

Correct. The earlier expressions are evaluated, but their values is discarded. So why use a comma operator in the real world? Because you want the side-effects of the expression. I find that they come up most in for() loops:

for (x=something, y=something_else; x < limit; ++x) ...
This code initializes x and y in the for loop.
Topic archived. No new replies allowed.