Sanya Pandey
Sanya Pandey

Reputation: 31

diffrence in working of post increment operator with and & or operator

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

Answers (1)

Sourav Ghosh
Sourav Ghosh

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 to 0, 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 1
  • b++ is evaluated, becomes 2
  • c++ is not evaluated, remains 2
  • the result of || 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

Related Questions