外部ライブラリから次のタイプがあるとします。
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
開発者に平和はありません...