Search code examples
c++operator-precedence

Getting different result when printing expression written in reverse order


Why I'm getting different result on the 3rd line? The output is:

1
1
0
1

Shouldn't I receive at the line no. 3 also the output 1 instead of 0? It has the same syntax as the other lines.

#include <iostream>
using namespace std;

int main()
{
    int x = -3;
    bool a = (x % 2 == 1) || (x < 0);
    bool b = (x < 0) || (x % 2 == 1);
    cout << a << "\n";                              // line 1
    cout << b << "\n";                              // line 2
    cout << (x % 2 == 1) || (x < 0); cout << "\n";  // line 3
    cout << (x < 0) || (x % 2 == 1); cout << "\n";  // line 4
}    

Solution

  • Because of operator precedence, which operator<< has higher than operator||, only the

    (x % 2 == 1)
    

    part is printed. The rest is like doing cout || (x < 0);. (note that std::cout, like any other std::basic_ios derived stream is implicitly convertible to bool)

    With parentheses, it looks like this:

    (cout << (x % 2 == 1)) || (x < 0);
    

    Line 4 printed 1, because (x < 0) was true and you switched the operands - this should be clear now.

    Solution: parenthesize the operator|| call:

    cout << (x % 2 == 1 || x < 0);
    

    Parentheses around operator||'s operands are, on the other hand, redundant.