The IO library redefines the bitwise >> and << operators to do input and output. Even though many programmers never need to use the bitwise operators directly, most programs do make extensive use of the overloaded versions of these operators for IO. When we use an overloaded operator, it has the same precedence and associativity as is defined for the built-in version of the operator. Therefore, programmers need to understand the precedence and associativity of these operators even if they never use them with their built-in meaning as the shift operators.
The IO Operators Are Left Associative
Like the other binary operators, the shift operators are left associative. These operators group from left to right, which accounts for the fact that we can concatenate input and output operations into a single statement:
- cout << "hi" << " there" << endl;
executes as:
- ( (cout << "hi") << " there" ) << endl;
In this statement, the operand "hi" is grouped with the first << symbol. Its result is grouped with the second, and then that result is grouped to the third.
The shift operators havemidlevel precedence: lower precedence than the arithmetic operators but higher than the relational, assignment, or conditional operators. These relative precedence levels affect how wewrite IO expressions involving operands that use operators with lower precedence. We often need to use parentheses to force the right grouping:
- cout << 42 + 10;
- cout << (10 < 42);
this expression says to “write 10 onto cout and then compare the result of that operation (e.g., cout) to 42.”