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