Shift Operators (aka IO Operators) Are Left Associative

Image

Although many programmers never use the bitwise operators directly, most programmers do use overloaded versions of these operators for IO. An overloaded operator has the same precedence and associativity as the built-in version of that operator. Therefore, programmers need to understand the precedence and associativity of the shift operators even if they never use them with their built-in meaning.

Because the shift operators are left associative, the expression

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 with the third.

The shift operators have midlevel precedence: lower than the arithmetic operators but higher than the relational, assignment, and conditional operators. These relative precedence levels mean we usually have to use parentheses to force the correct grouping of operators with lower precedence.

cout << 42 + 10;   // ok: + has higher precedence, so the sum is printed
cout << (10 < 42); // ok: parentheses force intended grouping; prints 1
cout << 10 < 42;   // error: attempt to compare cout to 42!

The last cout is interpreted as

(cout << 10) < 42;

which says to “write 10 onto cout and then compare the result of that operation (i.e., cout) to 42.”


Exercises Section 4.8

Exercise 4.25: What is the value of ~'q' << 6 on a machine with 32-bit ints and 8 bit chars, that uses Latin-1 character set in which 'q' has the bit pattern 01110001?

Exercise 4.26: In our grading example in this section, what would happen if we used unsigned int as the type for quiz1?

Exercise 4.27: What is the result of each of these expressions?

unsigned long ul1 = 3, ul2 = 7;

(a) ul1 & ul2

(b) ul1 | ul2

(c) ul1 && ul2

(d) ul1 || ul2


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset