OR and AND in C

I have doubts about the program below.

int main() { int i = -3,j = 2, k = 0,m; m = ++i || ++j && ++k; printf("%d %d %d %d\n", i, j, k, m); return 0; } 

I get output as -2 2 0 1 .

In the OR operation, if the first value is true, it will not evaluate the second, therefore i = -2 and j =2 . Then operation I. is performed. It will check that both values ​​are true. Therefore, if k = 1 , then m = 1 . Thus, the output should be -2 2 1 1 . I run and check and get the output as -2 2 0 1 , but I could not figure out how to do this.

+6
source share
2 answers

You used a short circuit or. Since ++ I am evaluated to -2, which is not 0, these are short circuits and do not evaluate the rest of the expression. As a result, neither j nor k increase.

Note also that the short-circuit operators, || and & & are left associative and that || has a higher priority than & &. As a result, || first, and early exits if the left side evaluates to true, and && & early exits if the left side evaluates to false.

EDIT: Fixed bug with explaining priority.

+8
source

Nothing after evaluation || , since the result of the expression ++i is nonzero.

+6
source

Source: https://habr.com/ru/post/891337/


All Articles