Thread: a little puzzle

1. a little puzzle

here's an interesting little puzzle I found on another board:

given the following sequence:

int a=0, b=0, c=0, d=0;
b = ( a++, a++, 6+a );
d = ( c++, 6+c, c++ );

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;

fill in the expected output for each variable below:
a =
b =
c =
d =

and explain your reasoning. Indicate any possible non-defined behaviors but assume the behaviors occur as expected.

2. a = 2
b = 8
c = 2
d = 1

It's due to the comma operator....this operator evaluates the left, but then discards the value....only the furthest right value is assigned in this case.

For "b = ( a++, a++, 6+a );" nothing is assigned from the 2 "a++" unary operations, but a is incremented each time. So the assignment is "b = 6+2" which is 8 and at that point, a is 2

For "d = ( c++, 6+c, c++ ); " , c is first incremented, but the middle evaluation is discarded (and it doesnt change the value of c). So all that is assigned is "d = c++" and at that point, c has been incremented once (postfix increment operator does not take effect until after the assignment). So d is 1 and c is 2.

Nice little puzzle....but if you understand the comma operator it's fairly easy to understand

3. Excellent analysis and explanation, maybe even better than on the other board!

I thought the little details in terms of the effect of the comma operator (I'd never seen a comma used like that before) and the difference in effect of the increment operator versus the addition operator on the variable it was associated with (all of which you explained wonderfully) was interesting.

4. Thanks for clearing that up for me, Fordy.

5. that's interesting... i've never seen that done before...

Popular pages Recent additions