C: Is there any wrong understanding about short-circuit evaluation?

80 views Asked by At

Hi I have little confused about logical operator.

According to KNK C chapter 5 exercise 3-4.

int i=1;
int j=1;
int k=1;
    
printf("%d\n",++i || ++j && ++k);
printf("%d %d %d",i,j,k);

I thought the result is 1\n 2 1 2 due to the short -circuit evaluation like ((++i || ++j) && ++k ).

But the answer is 1\n 2 1 1.

Why does variable k increase?

1

There are 1 answers

1
Ted Lyngmo On

From C Operator Precedence:

Precedence Operator Description Associativity
11 && Logical AND Left-to-right
12 || Logical OR Left-to-right

Since && has precedence 11 and || has 12, the expression ++i || ++j && ++k is equal to this:

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

Left-to-right associativity makes it evaluate ++i first, concludes that it's true and short-circuits so (++j && ++k) will not be evaluated.

The result is therefore

1
2 1 1