Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

operator<< with cout and precedence

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.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading