user8577930
user8577930

Reputation: 193

Ambiguity when using << >> operators

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?

Upvotes: 1

Views: 106

Answers (3)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

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.

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 180415

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.

Upvotes: 2

Yksisarvinen
Yksisarvinen

Reputation: 22176

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; 

Upvotes: 2

Related Questions