Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is overflow of an unsigned bit field guaranteed to wrap-around?

Details

The reference for bit fields at cppreference presents the following example:

#include <iostream>
struct S {
 // three-bit unsigned field,
 // allowed values are 0...7
 unsigned int b : 3;
};
int main()
{
    S s = {7};
    ++s.b; // unsigned overflow (guaranteed wrap-around)
    std::cout << s.b << '\n'; // output: 0
}

Emphasis on the guaranteed wrap-around comment.

However, WG21 CWG Issue 1816 describe some possible issues with unclear specification of bit field values, and [expr.post.incr]/1 in the latest standard draft states:

The value of a postfix ++ expression is the value of its operand. ...

If the operand is a bit-field that cannot represent the incremented value, the resulting value of the bit-field is implementation-defined.

I'm unsure, however, if this applies also for wrap-around of unsigned bit fields.

Question

  • Is overflow of an unsigned bit field guaranteed to wrap-around?
like image 798
dfrib Avatar asked Jan 15 '19 17:01

dfrib


1 Answers

Both [expr.pos]/1 and [expr.ass]/6 agree that integer overflow on a (signed or unsigned) bit-field is implementation defined.

[expr.pos]/1

[...] If the operand is a bit-field that cannot represent the incremented value, the resulting value of the bit-field is implementation-defined.

[expr.ass]/6

When the left operand of an assignment operator is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

I've fixed the cppreference page. Thank you for noticing.

like image 50
YSC Avatar answered Oct 30 '22 11:10

YSC