How are logical expressions that include increment and decrement operators evaluated in C?

int a = 0, b= 1, c = 1;
if (c-- || ++a && b--)

I know that the precedence for && is the highest here. So what happens? Does it start from && and then looks at the expression on its left which is (c– || ++a) and evaluates that first?

I have been experimenting for a while with different expressions and I just can’t wrap my head around it. Thanks in advance.

Edit: I would have used parenthesis if I could but this is a uni question so I don’t really have a say

>Solution :

Operator precedence does not directly influence evaluation order. What it does do is dictate how operands are groups. And since && has higher precedence than || as you noted, your expression is equivalent to:

(c-- || (++a && b--))

Given that the && operator uses short circuit evaluation, ++a would be evaluated before ++b. However, the entire subexpression ++a && b-- is the right side of the || operator which also uses short circuit evaluation, which means the left side, i.e. c-- would get evaluated first.

Since c-- evaluates to 1, the right side of the || operator, i.e. ++a && b--, is not evaluated. So c gets decremented and a and b are left unchanged.

Leave a Reply