4

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).

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Alexander
  • 1,068
  • 6
  • 22
  • 3
    Please note that `undefined behavior` is not the same as `implementation-defined result`. The former can literally make anything happen, the latter ensures that the result is documented in the compiler/architecture you are using (if it is compliant). As an example, `sizeof int` is implementation-defined, `*nullptr` is undefined – pqnet Jul 04 '18 at 13:46
  • 1
    @pqnet: We all may know what you meant twith the last one, though I really want to point out that `*nullptr` is ill-formed, while `*(int*)nullptr` is UB. – Deduplicator Jul 07 '18 at 01:04

1 Answers1

9

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.

llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • And the same standard defines that `bitset operator>>(size_t pos) const noexcept` returns `bitset(*this) >>= pos` (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf, page 539). – Shlublu Jul 04 '18 at 13:59