Why does this code contains colon in struct?

孤街浪徒 提交于 2021-02-05 09:31:11

问题


Please explain how this code is executing.why we has used ":" in structures.what is the use of colon in structures.what should be the output of sizeof operator.

#include <stdio.h>
int main()
{
struct bitfield {
    signed int a : 3;
    unsigned int b : 13;
    unsigned int c : 1;
};
struct bitfield bit1 = { 2, 14, 1 };
printf("%ld", sizeof(bit1));
return 0;
}

回答1:


The : operator is being used for bit fields, that is, integral values that use the specified number of bits of a larger space. These may get packed together into machine words to save space, but the actual behavior is implementation defined.

Now, the question "what should be the output of the sizeof operator" is straightforward but the answer is complicated.

The sizeof operator says it returns the number of bytes, but the definition of "bytes" is not necessarily what you think it is. A byte must be at least 8 bits, but could be more than that. 9, 12, and 16 bits are not unheard of.

sizeof(int) for a given platform can vary depending on the architecture word size. Assuming a byte size of 8 bits, sizeof(int) might be 2, 4, or 8. Possibly more. With a byte size of 16, sizeof(int) could actually be 1.

Now, remember I said that whether the bit fields get packed is implementation dependent? Well, that will make a big difference here. Each bit field could get put into a separate word. Or they all may be packed into one.

Most likely, you're on an Intel platform with 8-bit bytes and 32 or 64 bit ints, and the compiler will probably pack the bit fields. Therefore your sizeof(bit1) is likely to be 4 or 8.




回答2:


It's a part of syntax of bit fields. Here it means that a occupies 3 bits, b 13 bits and c only 1 bit. Of course the structure will not occupy only 17 bits in memory, as it must be aligned to bytes as the smallest addressable memory unit, so sizeof(bit1) will be at least 3 bytes (probably it will be aligned to some value related to a machine word, e.g. 4 bytes). You can read more about the alignment here: Structure padding and packing. I assumed that 1 byte is 8 bits size but there are some old or exotic architectures where bytes have another size.



来源:https://stackoverflow.com/questions/62216598/why-does-this-code-contains-colon-in-struct

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