Reputation: 455
I expected b to be 3.
is this an undefined behavior?
or the result could be predicted?
but i thought b would be 3.
and c would be 2.
the output i got is 1 2 1
please explain
#include<stdio.h>
int main()
{
int a = 0;
int b = 1;
int c = (a++ >b++ )? a++ : b++;
printf("%d %d %d",a,b,c);
return 0;
}
Upvotes: 1
Views: 739
Reputation: 284927
That's what I get, and I agree it's guaranteed to be that. There is a sequence point after evaluating the first operand (the condition) before going to the second or third operand. So it goes like this:
(a++ >b++ )
evaluates to:
0 > 1
which is 0.
After that, a
is 1 and b
is 2.
Since it was false:
b++
is evaluated. The result is 2 (which is assigned to c
), and afterwards b
is 3.
If that's the exact code, your compiler is buggy. It's not even a question of order. Even if the third operand were evaluated before the first (which would be wrong), b
should still be 3.
I am using GCC 4.6.3, but the result will be the same in all standards-compliant compilers.
Upvotes: 4
Reputation: 182674
It's defined behavior, there's a sequence point between the first operand of ?:
and second or third one.
So after evaluating a++ < b++
, a = 1 and b = 2. Then the third operand gets selected. Thus c gets assigned b++
. So c = 2 and then b = 3.
The C11 standard says:
6.5.15 Conditional operator
The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated).
Upvotes: 2