coperators

Confusion regarding precedence of C operators


I"m quite confused about the following block of code:

int a = 1, b = 2, c = 3;

printf("%d ", c - 3 && b++ > c);

printf("%d %d %d", a, b, c);

Initially, I thought that the output would be 0 1 3 3 since b would become 3 due to the side effect of the post-fix operator. But, the output I am getting is 0 1 2 3. Why is this?

Specifically, to evaluate c - 3 && b++ > c I used the C operator precedence table (https://en.cppreference.com/w/c/language/operator_precedence#cite_note-1) to determine the operator precedence. Postfix increment operator has much higher precedence than the logical AND operator. So why is the output the way it is? Do logical operators somehow bypass operator precedence in C?


Solution

  • Operator precedence dictates how operands are grouped, not the order in which they are evaluated. So this:

    c - 3 && b++ > c
    

    Parses as this:

    (c - 3) && ((b++) > c)
    

    The logical operators && and || have what's referred to as short circuit behavior, which means if the result can be determined from just the left operand then the right operand is not evaluated.

    The left operand of && is c - 3. This evaluates to 0, which means the entire && expression evaluates to 0 and the right operand, i.e. b++ > c is not evaluated, so b is not incremented.