Stefan12
Stefan12

Reputation: 21

Why doesn't the variable increment itself?

I am having trouble understanding this piece of code here. My question is why doesn't the post-increment work on the variable j? Seems like the line never gets executed and it ends up printing 0 0 instead of 0 1?

#include <stdio.h>

int main() {
    int i = 0, j = 0;
    (i == 0) || j++;
    printf("%d %d", i, j);
}

I would appreciate if someone explained to me where I'm wrong, thank you!

Upvotes: 2

Views: 85

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311010

The second operand of the logical OR operator is not evaluated if the first operand (sub-expression) yields true.

In this expression

(i == 0) || j++;

i == 0 is true so the second operand j++ is not evaluated.

If you will rewrite the expression like

(i == 0) && j++;

then the second operand (sub-expression) will be evaluated.

From the C Standard (6.5.13 Logical AND operator)

4 Unlike the bitwise binary & 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 equal to 0, the second operand is not evaluated.

and (6.5.14 Logical OR operator)

4 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.

Upvotes: 10

Blaze
Blaze

Reputation: 16876

(i == 0) evaluates to 1, so the result of the || is 1. It doesn't execute the j++ in this case. If it was (i == 1) || j++; instead, for instance, then j would be increased.

This is explained here:

There is a sequence point after the evaluation of lhs. If the result of lhs compares unequal to zero, then rhs is not evaluated at all (so-called short-circuit evaluation)

Upvotes: 2

Related Questions