The following is not undefined behavior in modern C:
union foo
{
int i;
float f;
};
union foo bar;
bar.f = 1.0f;
printf("%08x
", bar.i);
and prints the hex representation of 1.0f.
However the following is undefined behavior:
int x;
printf("%08x
", x);
What about this?
union xyzzy
{
char c;
int i;
};
union xyzzy plugh;
This ought to be undefined behavior since no member of plugh
has been written.
printf("%08x
", plugh.i);
But what about this. Is this undefined behavior or not?
plugh.c = 'A';
printf("%08x
", plugh.i);
Most C compilers nowadays will have sizeof(char) < sizeof(int)
, with sizeof(int)
being either 2 or 4. That means that in these cases, at most 50% or 25% of plugh.i
will have been written to, but reading the remaining bytes will be reading uninitialized data, and hence should be undefined behavior. On the basis of this, is the entire read undefined behavior?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…