Reputation: 409
I came across the following piece of code.
int main()
{
int i=1,j=2;
int a=i--?printf("%d",i):j--;
printf(" %d %d %d",i,j, a);
return 0;
}
The output is 0 0 2 1.
I understand the rest of the output except the first 0.
Please help.
Thanks.
Upvotes: 0
Views: 78
Reputation: 46365
The first 0
is the value of i
, which was initialized as 1
then decremented in the second line.
More explicitly:
i = 1
(i--) - evaluates as True, then sets i to 0
printf("%d ", i) = prints '0'
j-- - skipped
printf("%d %d %d", i, j, a)
print i: 0
print j: 2 (unchanged)
print a: return value of first `printf` : character count (1)
As @tristopia pointed out in a comment, there are two closely related concepts in play here:
The key here is that the ?
of the ternary operator is such a sequence point - thus you are sure that i
will have been decremented before you get to the printf
statement.
Contrast this with code like:
i = 1;
a = 5 * i++ + (i = 2 * i--);
This leads to undefined behavior - there is nothing in the C standard that can tell you definitively what the value of a
or i
will be after the above. When should the value of i++
be stored back in i
? Before the decrement operation? How about the fact that we are assigning a result to i
? Does that come before, or after, the other "implicit store" operations? Most compilers will warn you when they come across such a line - if you have a specific order of operations in mind you should "force sequence points" by rewriting the code.
Upvotes: 2
Reputation: 7102
Well you're calling printf()
twice. The first one in the conditional operator prints the value of i
(0). When you created the variable a
it had a default value of 0, and i
became 0 after decrementing it with i--
, so the condition passed.
Then you have your second printf()
which prints i
again along with the other 2 values.
Upvotes: 1
Reputation: 639
The value of i doesn't decrement before the condition check is done on it (due to postfix decrement). The test evaluates to true as i is 1, resulting in printf getting executed. But just as the test of i is over, it gets decremented, which is what printf prints on screen.
Upvotes: 2