在结构中混合位域

Mixing bitfields in structures

挂在 geeksforgeeks 上关于位域,找到这个例子:

#include <stdio.h>

struct test {
    unsigned int x;
    long int y : 33;
    unsigned int z;
};

int main() {
    struct test t;
    unsigned int *ptr1 = &t.x;
    unsigned int *ptr2 = &t.z;
    printf("%d", ptr2 - ptr1);
    return 0;
}

结果输出为4,为什么呢? x占4个字节,y - 8,z - 4。地址x和z的差值一定是8?

此代码没有可确定的行为。如果没有一个非常具体的编译器,就不可能预测它的任何结果。

它包含以下实现定义的行为(引用自标准的附件 J):

— Whether a ‘‘plain’’ int bit-field is treated as a signed int bit-field or as an unsigned int bit-field (6.7.2, 6.7.2.1).

— Allowable bit-field types other than _Bool, signed int, and unsigned int (6.7.2.1).

— Whether a bit-field can straddle a storage-unit boundary (6.7.2.1).

— The order of allocation of bit-fields within a unit (6.7.2.1).

— The alignment of non-bit-field members of structures (6.7.2.1). This should present no problem unless binary data written by one implementation is read by another.

第二个评论也意味着编译器必须有一个非标准的扩展。

最重要的是,代码还取决于字节顺序,您无法知道位域中的哪些位是 MSB 和 LSB。