Saurabh Jaisinghani
Saurabh Jaisinghani

Reputation: 33

precedence and execution of the operators in the statement

can't understand how the boolean variable "check" is assigned 1 or 0. here 2 == 2 is true but the 2 is not equal to 3 so it should be false.....

/* practicing the precedence of assignment operator */

#include <stdio.h>

int main() {

    _Bool check;
    check = (2 == 2 != 3);

    printf("the value of _Bool is %d\n",check);


    return 0;
}

i expect the result to be false

Upvotes: 0

Views: 69

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Two things:

  • The equality operators have same precedence and left to right associativity, so (2 ==2 != 3) is the same as ((2 == 2) != 3) which is (1 != 3) which is true.
  • The equality operations return an int value as result, so using a _Bool (or, bool with stdbool.h) is not necessary.

Upvotes: 0

Lundin
Lundin

Reputation: 213458

Operator precedence is the same for == and !=, since they both belong to the same group equality operators. To separate operators with same precedence, we use operator associativity of that group, in this case left-to-right. Meaning that 2 == 2 != 3 is guaranteed to be parsed as (2 == 2) != 3. So we get:

  • 2 == 2 -> 1
  • 1 != 3 -> 1

Notably both == and != have higher precedence than =, so the parenthesis in your expression = (2 == 2 != 3) isn't needed (but good practice to use if you are uncertain about precedence).


Regarding order of execution/evaluation, that's another term not to confuse with operator precedence. The order of evaluation of the == and != operands in your expression is unspecified, meaning we can't know which one that will get executed first.

In this case it doesn't matter, but if we had this check = a() == b() != c();, it could have. Here, we can't know which of the 3 functions that are executed first. We only know that operator precedence says that the result of a should be compared with the result of b before the result of c, but the function c may still be executed first.

Upvotes: 0

J...S
J...S

Reputation: 5207

What actually happens is like this

(2 == 2 != 3)

becomes

(2 == 2) != 3)

which is

(1 != 3)

which in turn becomes

(1)

Perhaps what you needed was

(2 == 2 && 2 != 3)

Upvotes: 1

Related Questions