为什么这段代码在结构中包含冒号? [英] Why does this code contains colon in struct?

查看:48
本文介绍了为什么这段代码在结构中包含冒号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释这段代码是如何执行的.为什么我们在结构中使用:".结构中冒号的用途是什么.sizeof运算符的输出应该是什么.

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;
}

推荐答案

: 运算符用于 位字段,即使用较大空间的指定位数的整数值.这些可能会被打包成机器字以节省空间,但实际行为是由实现定义的.

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.

现在,sizeof 运算符的输出应该是什么"这个问题很简单,但答案很复杂.

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

sizeof 运算符 表示它返回字节数,但字节"的定义不一定是您认为的那样.一个字节必须至少为 8 位,但可以更多.9、12 和 16 位并非闻所未闻.

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) 可能因架构字的大小而异.假设字节大小为 8 位,sizeof(int) 可能是 2、4 或 8.可能更多.字节大小为 16 时,sizeof(int) 实际上可以是 1.

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.

很可能,您使用的是具有 8 位字节和 32 或 64 位 int 的 Intel 平台,并且编译器可能会打包位字段.因此,您的 sizeof(bit1) 可能是 4 或 8.

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.

这篇关于为什么这段代码在结构中包含冒号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆