什么是零宽度位域 [英] What is zero-width bit field

查看:25
本文介绍了什么是零宽度位域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
零长度位域的实际使用

为什么有些结构有零宽度位域,为什么需要它?

Why some structures have zero-width bit fields, and why is it required?

struct foo {
  int    a:3;
  int    b:2;
  int     :0; // Force alignment to next boundary.
  int    c:4;
  int    d:3;
};

int main()
{
        int i = 0xFFFF;
        struct foo *f = (struct foo *)&i;
        printf("a=%d
b=%d
c=%d
d=%d
", f->a, f->b, f->c, f->d);
        return 0;
}

以上程序的输出为

manav@os-team:~/programs/test$ ./a.out
a=-1
b=-1
c=-8
d=0

请解释为什么这些值都是负数,以及这些变量在结构体内部的内存布局?

Please explain why these values are negative, and the memory layout of these variables inside the structure?

推荐答案

来自 这是谷歌搜索的第一次命中:

长度为 0 的位域必须是未命名的.无法引用或初始化未命名的位域.零宽度位域可以导致下一个域在下一个容器边界上对齐,其中容器的大小与位域的基础类型相同.

至于问题的第二部分,您将结构中的一些位域设置为全 1,并且由于这些字段是有符号的,因此这会导致这些字段的值为负.如果将整个结构体设置为 1 并查看有符号和无符号表示中的值,则可以更有效地看到这一点,例如

As for the second part of your question, you set some of the bitfields in your struct to all 1s, and since these fields are signed then this results in a negative value for these fields. You can see this more effectively if you set the entire struct to 1s and look at the values in both signed and unsigned representations, e.g.

int main()
{
    struct foo f;
    memset(&f, 0xff, sizeof(f));
    printf("a=%d
b=%d
c=%d
d=%d
", f.a, f.b, f.c, f.d); // print fields as signed
    printf("a=%u
b=%u
c=%u
d=%u
", f.a, f.b, f.c, f.d); // print fields as unsigned
    return 0;
}

这篇关于什么是零宽度位域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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