Short circuit of logical expressions in C in this example

PROGRAM

#include <stdio.h>

int main(void)
{
    int i, j, k;

    i = 1; j = 1; k = 1;

    printf("%d ", ++i || ++j && ++k);
    printf("%d %d %d", i, j, k);

  return 0;
}

RESULT

1 2 1 1

I expected 1 1 2 2. Why? Because && takes precedence over ||. So I followed the following steps: 1) j added 1, so j now has a value of 2 ... 2) k added 1, so k now has a value of 2 ... 3) 2 & 2, estimated at 1 ... 4) There is no need for further evaluation as the correct operand || true, therefore the whole expression must be true due to the behavior of short circuits of logical expressions ...

Why am I wrong?

+4
source share
1 answer

Priority only affects grouping. &&has a higher priority than ||means:

++i || ++j && ++k

is equivalent to:

++i || (++j && ++k)

, ++j && ++k. - , ||, ++i , ++j && ++k .

+9

All Articles