The following is not undefined behavior in modern C:
union foo
{
int i;
float f;
};
union foo bar;
bar.f = 1.0f;
printf("%08x\n", bar.i);
and prints the hex representation of 1.0f.
However the following is undefined behavior:
int x;
printf("%08x\n", 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\n", plugh.i);
But what about this. Is this undefined behavior or not?
plugh.c = 'A';
printf("%08x\n", 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?
int x; printf("%08x\n", x);
an UB ? Casting an int to an unsigned int is a behavior defined, and not initialyzing a variable is not an UB, so why this code end up in a UB ? – Cookoutprintf("%f", 42)
is fine because42
can be implicitly converted todouble
? – Carolinacarolinedouble
, the level of compiler complexity required to support reading and writing a superimposeduint16_t
oruint32_t
would be far less than the level of compiler complexity required to recognize all reasonable code patterns via which a program might assemble bytes of a float into a longer integer type and later decompose that type into a sequence of bytes, and convert those patterns into a single 16-or-32-bit read and a single such write. – Sackcloth