c++ - 无符号位域的溢出是否保证回绕?

标签 c++ language-lawyer integer-overflow bit-fields

详情

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/

相关文章:

c - 结果我想不通

C++ 标记化字符串不可取消引用

C++ 找不到错误,+ 运算符重载将 2 个链表相加

c++ - 将 xvalues 转换为 lvalues 以传递给函数是否定义明确?

go - 为什么 "import"和ImportSpec之间可以出现多行注释,而PackageName和ImportPath之间不能?

php - ksort 不可预测的整数溢出

c++ - CUDA:对传递给 GPU 的数组的每个第 n 个点进行分组

c++ - Typedef 静态 std::list 数组

c++ - 为什么模板模板参数不允许在参数列表后出现 'typename'

c++ - 对 C++ 异常处理很困惑