假设我有来自外部库的以下类型:
union foreign_t {
struct {
enum enum_t an_enum;
int an_int;
} header;
struct {
double x, y;
} point;
};
假设以下代码片段将在不同平台和不同编译器上按预期工作是否安全?
struct pair_t {
double x, y;
};
union foreign_t foreign;
struct pair_t *p_pair;
p_pair = (struct pair_t *) &foreign;
p_pair->x = 1234;
p_pair->y = 4321;
/* Expected result: (1234, 4321) or something like that */
printf("(%lf, %lf)", foreign.point.x, foreign.point.y);
编辑:
按照严格的别名建议,我做了以下测试:
#include <stdint.h>
#include <stdio.h>
int main()
{
uint16_t word = 0xabcd;
uint8_t tmp;
struct {
uint8_t low;
uint8_t high;
} *byte = (void *) &word;
tmp = byte->low;
byte->low = byte->high;
byte->high = tmp;
printf("%x\n", word);
return 0;
}
上面这段看似无辜的代码并不可靠:
$ gcc -O3 -fno-strict-aliasing -otest test.c
$ ./test
cdab
$ gcc -O3 -fstrict-aliasing -otest test.c
$ ./test
abcd
开发商没有安宁...