What is the use of declaring different datatypes inside bitfields?

淺唱寂寞╮ 提交于 2019-12-06 03:27:26

Actually, the C standard only allows bitfields to be of type signed int or unsigned int (and _Bool in C99). If you can throw a short, long or char in there, that's a compiler extension.

As to why, the main reason is signedness. Consider:

struct {
   int s: 3;
   unsigned u: 3;
} bf;

bf.s = 7;
bf.u = 7;

Both of these bitfields are all ones. However, C preserves sign, so:

(int)bf.s == -1    // Because signed conversions preserve the sign bit
bf.s >> 1 == -1    // So do right shifts on signed values

while:

(int)bf.u == 7     // Because the source is unsigned and so just a series of bits
bf.u >> 1 == 3     // Unsigned right shifts are just moving bits around as well

For compilers that allow char, it's probably the same sort of thinking. The default signedness of char is implementation-defined so if you want a bitfield's signedness to match your compiler's char's signedness, you can define it as char.

The size is for the storage (or transportation) of the data. The data type is how you intend to use and process that information.

Using any other type than int for a bit-field is implementation-defined behavior. So without knowing what specific compiler you are using, there is no telling what that code does, or if it even compiles.

Bit-fields in general are very poorly defined by the standard, and therefore completely unportable. Since bit-fields are also pretty much a superfluous feature of the C language, it is most likely wiser to do bit manipulations using the bit-wise operators.

The only time that types inside a bitfield matter to me is signed vs. unsigned types. For fields wider than 1 , this can make a difference in how the data is interpreted during assignment.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!