Search code examples
cintegerlogical-operatorsshort-circuitinglogical-or

Using logical operators on integers in C


Logical OR and Logical AND operator on integers in C

Can you explain me why the values of a,b,c are 11,10,1 respectively. Why the value of b remains same as 10?

#include <stdio.h>
int main()
{
    int a,b,c;
    a=b=c=10;
    c = a++ || ++b && ++c;
    printf("%d %d %d",a,b,c);
    return 0;
}

Solution

  • First, let's look at the order of operations. The logical AND operator && has higher precedence than the logcial OR operator ||, so the expression parses as follows:

    c = a++ || (++b && ++c);
    

    Next, both || and && are short circut operators. This means that the left has side is evaluated first, and if the result can be determined solely from that then the right hand side is not evaluated.

    So a starts out with the value 10. a++ evaluates to the current value (10) while incrementing a as a side effect. This means the value 10 is the left hand side of ||. Because this is a non-zero value, the value of the entire expression is 1 and the right hand side ++b && ++c is not evaluated. Then this result is assigned to 1.

    So the end result is a is incremented to 11, c is assigned 1 because that is the value of the || expression, and b is unchanged.