Reputation: 31
This post-increment operator usage is confusing.
{int a=0,b=1,c=2,d;
d=a++||b++||c++
printf("%d %d %d %d",a,b,c,d);}
output is
1,2,2,1
value of c
did not increase but if I replace it with &&
operator it increases. Why?
Upvotes: 0
Views: 22
Reputation: 134336
Quoting C11
, chapter §6.5.14, (emphasis mine)
Unlike the bitwise
|
operator, the||
operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to0
, the second operand is not evaluated.
So, in your case,
d=a++||b++||c++
is the same as
d= ( (a++ || b++) || c++)
Then, the statement inside the first parenthesis is evaluated, first a++
(post-increment) evaluates to 0 (side-effect pending), so the RHS of the first ||
is evaluated, b++
, producing 1 and the result of the ||
operation is TRUE, yields 1.
That result, 1
, is the LHS of the second ||
. Hence, the RHS of the second ||
(c++
) is not evaluated anymore and the final result becomes TRUE, again yielding 1
, which gets stored in d
.
So, finally,
a++
is evaluated, becomes 1b++
is evaluated, becomes 2c++
is not evaluated, remains 2 ||
is stored in d
, that is TRUE, so stores 1.On the other hand, for logical AND &&
operator,
[...] If the first operand compares equal to 0, the second operand is not evaluated.
So, if you replace the last ||
with &&
, then for the outer statement, the LHS becomes 1 and the RHS evaluates, making c++
to be evaluated and incremented, as a side effect.
Upvotes: 2