0

I have the two codes as shown below:

#include <iostream>
int main() {
    int a = 4;
    if ( a == a--){
        std::cout << a << std::endl;
        std::cout << "HELLO"<<std::endl;
    }
    std::cout << a << std::endl;
    return 0;
}

Output is: 3

and for this:

#include <iostream>
int main() {
    int a = 4;
    if ( a == --a){
        std::cout << a << std::endl;
        std::cout << "HELLO"<<std::endl;
    }
    std::cout << a << std::endl;
    return 0;
}

Output is:

3
HELLO
3

According to C++ operator precedence, increment and decrement operator (for prefix and postfix) precedes relational opertor ==. Then the expected output for both should be same (here expected was: 3 for both), but actually it isn't.

Any help? Also if the above condition leads to undefined behavior then please explain why.

Rakholiya Jenish
  • 3,165
  • 18
  • 28

1 Answers1

2

operator precedence tells how to parse expression (add parenthesis), not the order of evaluation.

so --a == b is effectively parsed as (--a) == b and not --(a == b).

Jarod42
  • 203,559
  • 14
  • 181
  • 302