psyc0der
psyc0der

Reputation: 409

C Conditional Statement

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

Answers (3)

Floris
Floris

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:

  1. Post-fix operators: the value that is used in the expression is the value before increment takes place...
  2. Sequence point: a point in the code where "all side effects of previous evaluations will have been performed" - in other word, "everything that needs to have happened will happen before we pass this point". For example, any variable that was post-fix incremented is guaranteed to be incremented (and stored) when you pass the sequence point.

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

PaulG
PaulG

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

reza.safiyat
reza.safiyat

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

Related Questions