1

The << and >> operators have two meanings in C++, bit-shifting and stream operations. How does the compiler resolve this ambiguity when the meaning isn't obvious from context? Take this line for example: std::cout << 1 << 2 << std::endl; Would the output be 12, as if the second << were treated as a stream insertion, or 4, as if the second << were treated as a bit shift?

1
  • 2
    Related: Operator precedence is unaffected by operator overloading. So, same precedence rule as if << had one interpretation only.
    – Damien
    Feb 8, 2021 at 17:22

3 Answers 3

2

operator >> and operator << have left to right associativity. That means that with the addition of some parentheses, the actual expression is

((std::cout << 1) << 2) << std::endl;

and here you can see that with each call, the stream object, or the return of the stream expression, is used as the left hand side of each expression. That means all of the values will inserted into the stream.

2

There is no ambiguity, because compilers interprets the expression from left to right, so this:

std::cout << 1 << 2 << std::endl; 

is equivalent to:

((std::cout << 1) << 2) << std::endl; 
2

Consider that << has left-to-right associativity (see here) and that

std::cout << 1 << 2 << std::endl;

can be thought of as the short way of writing:

std::cout.operator<<(1).operator<<(2).operator<<(std::endl);

In other words: There is no ambiguity.

PS: Also consider that the "problem" you see is not only about two meanings of <<. The operator can be overloaded to have any meaning for a custom type. Nevertheless std::cout << custom_object_1 << custom_object_2; calls std::ostream& operator<<(std::ostream&,const custom_type&). For example: https://godbolt.org/z/fn3PTz.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.