What is the output of expression c = a>2+b!=6?

Viewed 520

Recently I came across this program.

#include <stdio.h>

int main() {
    int a = 10, b = 20, c;
    c = a > 2 + b != 6;
    printf("%d", c);
}

What is the logic behind the output being 1?

1 Answers

It depends on the precedence of the operators.

+ has higher precedence than > and > has higher precedence than !=.

a > 2 + b != 6

is evaluated as:

((a > (2 + b)) != 6)

or more specific:

((10 > (2 + 20)) != 6)

where (10 > (20 + 2)) is evaluated to 0, because 10 isn't greater than 22.

So the expression is unfolded to:

(0 != 6)

which evaluates to 1 because 0 is not equal to 6 -> (0 != 6) == 1.

Related