I'm using someone else's code that was written with an older compiler that mapped a special BOOL
type to an unsigned int
, but in my compiler it's mapped to a true bool
. In some places in his code he uses the bitwise shift operator <<
on the bool
type, which I had never seen before and my compiler surprised me when it didn't complain.
Is that valid C++? Does the bool
automatically get promoted to an int
or uint
?
I saw this related question, which provided some clarity on another issue, but it doesn't address the shift operators.
In C the shifts work as expected on unsigned values and on positive signed values - they just shift bits. On negative values, right-shift is implementation defined (i.e. nothing can be said about what it does in general), and left-shift is simply prohibited - it produces undefined behavior.
Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.
The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.
From Shift operators [expr.shift]
The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand
bool
is an integral type so the code is well formed (bool
is promoted to int
and result is an int
).
From [conv.prom], we show what integers the booleans get promoted to:
A prvalue of type
bool
can be converted to a prvalue of typeint
, withfalse
becoming zero and true becomingone
Afterwards, the shift behaves normally. (Thanks, @chris)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With