详情
reference for bit fields at cppreference给出以下示例:
#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 }
强调有保证的环绕评论。
然而,WG21 CWG Issue 1816描述一些可能存在的位字段值规范不明确的问题,以及 [expr.post.incr]/1在最新的标准草案状态:
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.
但是,我不确定这是否也适用于无符号位字段的回绕。
问题
- 是否保证无符号位域溢出?
最佳答案
两者都是[expr.pos]/1
和 [expr.ass]/6
同意(有符号或无符号)位域上的整数溢出是实现定义的。
[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.
我已经修复了 cppreference 页面。感谢您的关注。
关于c++ - 无符号位域的溢出是否保证回绕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54204113/