我不确定代码是否在断言转换中具有指针别名(或其他标准一致性问题).似乎指向联合类型的指针应该能够转换为第一个成员的指针,因为联合只由这两个结构组成,我认为对第一个成员的强制转换应该有效,但我不是确定这是否正确,或者我是否在过程中掩盖了填充细节.工会是否需要填补高位?
似乎这是未指明的行为?有没有人知道这是否被支持.我知道有一种替代的标准方法可以通过使用带有enum type
字段和struct container_storage
成员的结构来实现这一点,但考虑到此信息已经存在,这似乎是浪费空间struct contained
linux中的编译命令:gcc -std=c99 -Wextra -pedantic -fstrict-aliasing test.c && ./a.out && echo $?
返回0
#include
#include
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,严格别名,并通过联合进行转换
[2] 什么是严格别名规则?