c – 已签名的基础类型枚举的位域溢出

前端之家收集整理的这篇文章主要介绍了c – 已签名的基础类型枚举的位域溢出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这仅适用于C 11:

如果我有如下常规枚举:

enum TestType
{
Test0 = 0,Test1,Test2,Test3,Test4,Test5,Test6,Test7
}

和这样的打包结构:

struct
{
TestType a : 3
uint32_t b : 5
} TestStruct;

TestStruct.a在访问时是否保证等于任何有效的指定枚举值?或者编译器是否有可能分配已签名的基础类型,然后将位域a视为范围-4到3.

解决方法

Is TestStruct.a guaranteed to be equal to its assigned enum value?

不.您默认初始化TestStruct.如果这是在全局空间中,那么它将被初始化为零,并且a和b都将为0.

如果这是在块空间中,则不会发生初始化,这意味着a和b具有未指定的值.所有你知道的是,该值将在该类型的可表示范围内.具有值0的Test0根本不起作用.

如果你有

TestStruct{};

然后a和b将为零,因为你是初始化对象的值,在这种情况下,这意味着你零初始化它.你也可以使用

TestStruct{value1,value2};

为a和b分配特定值.

关于是否可以存储TestType的所有值的问题,我们必须查看[class.bit]/4的状态

[…]If the value of an enumerator is stored into a bit-field of the same enumeration type and the number of bits in the bit-field is large enough to hold all the values of that enumeration type ([dcl.enum]),the original enumerator value and the value of the bit-field shall compare equal.

强调我的

枚举的值由[dcl.enum]/8定义为

For an enumeration whose underlying type is fixed,the values of the enumeration are the values of the underlying type. Otherwise,for an enumeration where emin is the smallest enumerator and emax
is the largest,the values of the enumeration are the values in the range
bmin to bmax,defined as follows: Let K be 1 for a two’s complement representation and 0 for a ones’ complement or sign-magnitude representation. bmax is the smallest value greater than or equal to max(|emin − K,|emax|) and equal to 2M−1,where M is a non-negative integer. bmin is zero if emin is non-negative and −(bmax+K) otherwise. The size of the smallest bit-field large enough to hold all the values of the enumeration type is max(M,1) if bmin is zero and M+1 otherwise. It is possible to define an enumeration that has values not defined by any of its enumerators. If the enumerator-list is empty,the values of the enumeration are as if the enumeration had a single enumerator with value 0

所以在这种情况下,emin为0,emax为7,所以bmin为0,bmax等于或大于max(| emin | – K,| emax |)为7.如果我们必须等于2M-1使用3表示M然后我们也得到7.

我们有

The size of the smallest bit-field large enough to hold all the values of the enumeration type is max(M,1) if bmin is zero and M+1 otherwise.

并且bmin为零所以我们需要的最小位域是3,所以你可以保证TestType的所有值都适合a.

猜你在找的C&C++相关文章