The accepted answers to the questions here and here say that it's all about operator precedence and thus,
cout << i && j ;
is evaluated as
(cout << i) &&j ;
since the precedence of Bitwise-Operators is greater than that of Logical-Operators. (It's not the bitwise operator here, but it is the symbol itself which is setting the precedence.)
I wonder then why the following code doesn't output 1:
int x=2, y=1 ;
cout << x>y ;
since the precedence of Relational-Operators is greater than Bitwise-Operators; the last line should get treated as cout << (x>y) ;
.
I got a warning that overloaded operator<<
has higher precedence than a comparison operator.
What is the precedence of overloaded operator<<
in comparison to all other existing operators?
CodePudding user response:
someone tell what is the precedence of overloaded operator << in comparison to all other existing operators?
The inserter <<
has higher precedence than the relational operator<
, operator>
etc. Refer to operator precedence.
This means that cout << x>y
is grouped as(and not evaluated as):
(cout << x)>y;
Now, cout << x
returns a reference to cout
which is then used as the left hand operand of operator>
. But since there is no overloaded operator>
that takes cout
as left hand operand and int
as right hand operand you get the error saying exactly that:
error: no match for ‘operator>’ (operand types are ‘std::basic_ostream’ and ‘int’)
Note
Additionally, in your question you've used the phrase "is evaluated as" which is incorrect. The correct phrase would be "is grouped as".
CodePudding user response:
According to the C reference (https://en.cppreference.com/w/cpp/language/operator_precedence), the precedence of the bitwise shift operator is greater than the precedence of relational operators. cout <<
, despite being a I/O operation, is an overload of the bitwise shift operators.