结构位域最大大小(C99,C++)
位结构域的最大位宽是多少?
What is maximal bit width for bit struct field?
struct i { long long i:127;}
我可以在 struct 中定义一个位域,位域的大小最大为 128 位、256 位或更大吗?有一些超宽向量类型,例如 sse2(128 位)、avx1/avx2(256 位)、avx-512(下一个至强融核为 512 位)寄存器;以及 gcc 中的 __int128 等扩展.
Can I define a bit field inside struct, with size of bitfield up to 128 bit, or 256 bit, or larger? There are some extra-wide vector types, like sse2 (128-bit), avx1/avx2 (256-bit), avx-512 (512-bit for next Xeon Phis) registers; and also extensions like __int128 in gcc.
推荐答案
C99 §6.7.2.1,第 3 段:
C99 §6.7.2.1, paragraph 3:
指定的表达式位域的宽度应为具有的整数常量表达式不应该的非负值超过对象中的位数指定的类型,如果省略了冒号和表达式.如果值为零,声明不得有声明符.
The expression that specifies the width of a bit-field shall be an integer constant expression that has nonnegative value that shall not exceed the number of bits in an object of the type that is specified if the colon and expression are omitted. If the value is zero, the declaration shall have no declarator.
C++0xa §9.6,第 1 段:
C++0xa §9.6, paragraph 1:
... 常量表达式应为积分常数表达式值大于或等于零.积分常数的值表达式可能大于对象中的位数的表示 (3.9)位域的类型;在这种情况下额外的位用作填充位并且不参与价值位域的表示(3.9).
... The constant-expression shall be an integral constant expression with a value greater than or equal to zero. The value of the integral constant expression may be larger than the number of bits in the object representation (3.9) of the bit-field’s type; in such cases the extra bits are used as padding bits and do not participate in the value representation (3.9) of the bit-field.
所以在 C 中你根本不能这样做,而在 C++ 中它不会做你想要的.
So in C you can't do that at all, and in C++ it won't do what you want it to.
相关文章