cout unexpected print result with logical OR operator

Why does this code print 0?

#include <iostream>

using namespace std;

int main()
{
    cout<< 0 || 7;

    return 0;
}

In Javascript, the result of that operation would be 7.

>Solution :

Due to Operator Precedence, << has a higher precedence than ||, so the compiler implicitly interprets cout << 0 || 7 as-if you had written (cout << 0) || 7. To process || first, you need to use your own parenthesis to tell the compiler that you want cout << (0 || 7) instead.

However, this will output 1, not 7 as you are expecting, because C++’s logical OR returns an integer 1 if either operand evaluate to a non-zero value, otherwise it returns an integer 0 instead. Unlike Javascript’s logical OR, which returns the actual value of the first operand that is not equal to zero.

Leave a Reply