Post-increment and pre-increment operator in C

c, post-increment, pre-increment

Solution

The logical or, `||` short-circuits, and after

++i && ++j

the value of the entire expression is determined, so the right operand of the `||` isn't evaluated.

m=++i && ++j || ++k;

is parenthesized `m = (++i && ++j) || ++k;` since the `&&` has higher precedence than the `||`.

The short-circuiting of the logical operators means that the right operand is only evaluated when the evaluation of the left has not yet determined the final result, for `||` that means the right operand is only evaluated if the left evaluated to 0, and for `&&`, the right operand is only evaluated if the left evaluated to a nonzero value.

So first `++i && ++j` is evaluated, and for that, first `++i` is evaluated. `i` had the value `-3` before, so `++i` evaluates to `-2`, which is not 0, hence the `++j` is evaluated too. `j` had the value `2` before, so `++j` evaluates to `3`, which is again nonzero, and thus `++i && ++j` evaluates to 1 (true). Since the left operand of the `||` is not zero, its result is already determined (to be 1), and the right operand isn't evaluated, thus `k` remains unchanged and `m` is set to 1.

Problem

Why is k not getting incremented whereas,i and j are getting incremented in the same expression.And i also want to know what is the output of the program.I am getting the output as -2 3 1 0 ``` #include <stdio.h> void main() { int i=-3, j=2, m, k=0; m=++i && ++j || ++k; printf("%d %d %d %d", i, j, m, k); } ```

Original source

Related problems