Search code examples
c++streambit-shift

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?


Solution

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