Reputation: 37
I am studying C++ from Primer 5th edition. One of the questions is:
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?
What i am confused with is will the compiler convert the 'q' to 32-bit int before ~ or before <
As far as I understand it should work like so:
'q' = 01110001
~'q' = 10001110
~'q' << 6 = 00000000000000000010001110000000
Am I right?
Upvotes: 2
Views: 708
Reputation: 171117
The operator ~
performs integral promotions on its operand (C++11, [expr.unary.op]§10
). Which means it will convert the char
to int
before doing the complement. So it will go like this:
'q' == 01110001
~ 'q' == ~ 00000000000000000000000001110001
~ 'q' == 11111111111111111111111110001110
Then comes a problem. We see the value of ~ 'q'
is negative. Left-shifting a negative value has undefined behaviour ([expr.shift]§2
). (Thanks to @colombien's answer for pointing out this last part)
Upvotes: 8
Reputation: 149
I guess the answer is here: Bitwise operators and signed types
The expression
~'q' << 6
results in undefined behavior.
Upvotes: 2