我不确定代码是否在asserts强制转换中存在指针别名(或其他标准一致性问题)。看来,指向联合类型的指针应该能够转换为第一个成员的指针,并且因为联合只由这两个结构组成,所以我认为对第一个成员的转换应该可行,但我不是确定如果这是正确的,或者如果我在这个过程中填充细节的细节。工会是否需要填充高位?与普通第一成员结合的结构体
看起来这是不明确的行为?有没有人有任何洞察力,这是否是支持的。我知道有利用结构与enum type
场和struct container_storage
成员这样做的另一种标准的方式,但它似乎是浪费空间考虑,这个信息已经在struct contained
编译命令在Linux中:gcc -std=c99 -Wextra -pedantic -fstrict-aliasing test.c && ./a.out && echo $?
返回0
#include <stdlib.h>
#include <assert.h>
enum type {type_a = 1, type_b = 2};
struct contained {
int some_other_field;
enum type type;
};
struct container_a {
struct contained contained;
int test;
};
struct container_b {
struct contained contained;
char test;
};
union container_storage {
struct container_a container_a;
struct container_b container_b;
};
int
main(int argc, char **argv)
{
union container_storage a =
{.container_a = {.contained = {.type = type_a}, .test = 42}};
union container_storage b =
{.container_b = {.contained = {.type = type_b}, .test = 'b'}};
assert(((struct contained *)&a)->type == type_a);
assert(((struct contained *)&b)->type == type_b);
return EXIT_SUCCESS;
}
参考文献:
[1] gcc, strict-aliasing, and casting through a union
[2] What is the strict aliasing rule?
很高兴听到。我试图挖掘C99规范,但我似乎无法在任何地方找到它。谢谢! – backscattered