How exactly does the ?: operator work in C?
Beacuse the condition is false, therefore the false
case will happen: c-1
, but since you incremented c
in the condition by c++
, therefore c
is now 12
. The result thus 12 - 1 which is 11.
EDIT: What OP misunderstood was the post increment.
So what actually happen is like this:
#include<stdio.h>
int main(void)
{
int b=12, c=11;
int d;
if (b == c) { // 12 == 11 ? -> false
c = c + 1;
d = c + 1;
} else { // this executes since condition is false
c = c + 1; // post increment -> c++ -> c = 12 now
d = c - 1; // 12 - 1 = 11 -> d = 11
}
printf("d = %i\n", d);
}
According to the C Standard (6.5.15 Conditional operator)
4 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). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), converted to the type described below.110)
So in the initializing expression of this declaration
int d = (b == c++) ? (c+1) : (c-1);
the variable b
is compared with the value of the variable c
because the post-increment operator returns the value of its operand before incrementing it.
As the values are not equal each other (b
is set to 12 while c
is set to 11) then the sub-expression (c-1)
is evaluated.
According to the quote there is a sequence point after evaluation of the condition of the operator. It means that after evaluation of the condition c
has the value 12
after applying the post-increment operator to the variable c
. As a result the variable d is initialized by the value 1
(12 - 1
).
In int d = (b == c++) ? (c+1) : (c-1);
:
- The value of
c++
is the current value ofc
, 11. Separately,c
is incremented to 12. b == 11
is false, sinceb
is 12.- Since
(b == c++)
is false,(c-1)
is used. Also, the increment ofc
to 12 must be completed by this point. - Since
c
is 12,c-1
is 11. d
is initialized to that value, 11.