Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you bitwise shift a bool in C++?

Tags:

c++

bit-shift

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.

like image 278
Phlucious Avatar asked Nov 22 '17 16:11

Phlucious


People also ask

How does bitwise Shift work in C?

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.

Can you bit shift an integer?

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.

Are shift operators bitwise?

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.


1 Answers

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 type int, with false becoming zero and true becoming one

Afterwards, the shift behaves normally. (Thanks, @chris)

like image 127
AndyG Avatar answered Oct 16 '22 03:10

AndyG