Search code examples
c++operator-precedence

What a+=b == c does in C++?


I have this piece of code that has been bugging me the whole day, and I think I need some help with it, here is the code is written in C++:

    int main()
    {
        int a = 3, b = 4;
        if (a+=2 == b) {
            cout << a << endl;
            cout << "True" << endl;
        }
        return 0;
    }

The if statement will always be true no matter what values of a and b are, and the value of a will not be changed (i.e. The cout for a will print the value of a when it is first assigned. However, when I put a pair of parentheses to (a+=2), the code will be executed as I expected. So my question is why does the expression in the if statement always be true?


Solution

  • Operator precedence means a+=2 == b will be grouped as a += (2 == b). So a is incremented with the result of the comparison between b and 2.

    The comparison result is a boolean, so when converted to an integer it will yield 0 or 1.

    Since compound addition (+=) also evaluates to the result of the operation, the condition in the if statement will check the value of a is not 0 after adding 0 or 1 to it. Since a is initialized to 3, the condition is true either way.