Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is shifting std::bitset<N> more than N positions undefined behavior?

As discussed in Is right shift undefined behavior if the count is larger than the width of the type?, shifting a value is undefined if the number of bit shifts exceeds the effective operand size.

Thus, in the following, the value of bar is undefined:

uint32_t foo = 123;
uint32_t bar = (foo >> 33);

Are such shift operations well defined for std::bitset? As in:

std::bitset<32> foo(123);
std::bitset<32> bar(foo >> 33);

And in which official document can I find such information?

The case is not explicitly stated on cppreference (https://en.cppreference.com/w/cpp/utility/bitset/operator_ltltgtgt).

like image 573
Alexander Avatar asked Jan 03 '23 04:01

Alexander


1 Answers

The result is defined as 0 by the standard, [bitset.members]/9:

bitset& operator>>=(size_t pos) noexcept;

9 Effects: Replaces each bit at position I in *this with a value determined as follows:

(9.1) If pos >= N - I, the new value is zero;

(9.2) If pos < N - I, the new value is the previous value of the bit at position I + pos.

like image 184
llllllllll Avatar answered Jan 05 '23 17:01

llllllllll