Search code examples
clogical-operatorsansi-c

Precedence of 'or' and 'and' operators in C


In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a,b,c,d;
    a =1;
    b = c = 10;
    d = a|| --b&&--c;
    printf("%d\n",c);
    printf("%d\n",a);
    printf("%d\n",d);
    return 0;
}

Solution

  • Precedence only determines which operands are grouped with which operators - it does not control the order in which expressions are evaluated.

    In your example, it means the expression is parsed as

    a || (––b && ––c)
    

    Both || and && force left-to-right evaluation1. Both introduce a sequence point (IOW, the left hand operand will be evaluated and all side effects will be applied before the right hand operand is evaluated).

    Both operators short-circuit - if the left operand of || evaluates to non-zero, then the result of the expression is 1 (true) regardless of the value of the right operand, so the right operand isn’t evaluated at all. If the left operand of && is 0, then the result of the expression is 0 (false) regardless of the value of the right operand, so the right operand isn’t evaluated at all.

    In your expression, a is evaluated first. It has a non-zero value (1), so ––b && ––c is not evaluated.


    1. Along with the ?: and comma operators. All other operators (arithmetic, equality, subscript, etc.) do not force a particular order of evaluation.