无符号位域的溢出是否保证回绕?
Is overflow of an unsigned bit field guaranteed to wrap-around?
详情
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 describe some possible issues with unclear specification of bit field values, and [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
and [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 页面。感谢您的关注。
详情
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 describe some possible issues with unclear specification of bit field values, and [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
and [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 页面。感谢您的关注。