# a little puzzle

• 10-31-2003
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.
• 10-31-2003
Fordy
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
• 10-31-2003