Home > Back-end >  cout unexpected print result with logical OR operator
cout unexpected print result with logical OR operator

Time:08-06

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.

CodePudding user response:

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 not output 7 as you are expecting. C 's logical OR returns a bool, either true if either operand evaluates to true, otherwise it returns false. operator<< is overloaded to take a bool as input, and it will output either 1/0 or true/false depending on whether cout's boolalpha flag is enabled or not.

Unlike Javascript's logical OR, which returns the actual type and value of the first operand that is not equal to zero. Which is why equivalent Javascript code returns 7 instead.

CodePudding user response:

As already hinted at in the comments, the << operator (originally intended as the left bitwise shift operator and later commandeered for output) has higher precedence than ||. So your expression is actually

(cout <<  0) || 7;

That is, it prints 0, and then does a Boolean OR between the result of that call (which is cout; output streaming operators always return the stream) and 7.

The result will be discarded, but for what it's worth an output stream evaluates to true as a Boolean if and only if there are no errors in the stream, so this expression (if it were assigned to a variable or something) would return the output stream if the print was successful, or 7 if it failed.

  •  Tags:  
  • c
  • Related