Search code examples
c++if-statementcomparison-operators

How does the compiler evaluates expression with multilple comparison operators inside of the if-statement?


So I have this program that returns "result: true"

if (true == false != true) {
    cout << "result: true";
}
else {
    cout << "result: false";
}

even if we flip the comparison operators inside of the if-statement, the compiler still evaluates the expression to be true

if (true != false == true)

My question is:

  1. How does the compiler actually evaluates the expression?
  2. and to which comparison operator out of the two present inside of the if-statement, preference is given?

Solution

  • The answer to both of your questions is operator precedence. The == and != operators get the same precedence, meaning they will be evaluated in the order given.

    So in true == false != true, is evaluated as (true == false) != true first statement true==false being false, the full statement now becomes false!=true which evaluates to true

    Similarly, 2nd statement true != false == true becomes (true != false) == true which evaluates to true at the end


    EDIT:

    After reading @Pete's comment, I did some more reading. Apparently there is an associativity property related to these kinds of situations

    From https://en.cppreference.com/w/cpp/language/operator_precedence

    Operators that have the same precedence are bound to their arguments in the direction of their associativity. For example, the expression a = b = c is parsed as a = (b = c), and not as (a = b) = c because of right-to-left associativity of assignment, but a + b - c is parsed (a + b) - c and not a + (b - c) because of left-to-right associativity of addition and subtraction.