Quote:
Toby Weingartner writes:
> ... tell me why the following piece of code is illegal:
There is no such term as "illegal" in the standard.
Quote:
> union a_union {
> int i;
> double d;
> };
> int f(void) {
> a_union t;
Syntax error: you have not defined any type named "a_union". Either
the initial declaration should be changed to a typedef, or the above
line should read:
union a_union t;
Reread questions 2.1 and 2.2 in the FAQ list. Or in the current standard,
read sections 6.5.2.3 and 6.5.6.
Quote:
> int *ip;
> t.d = 3.0;
> ip = &t.i;
> return *ip;
> }
This part of the code is correct, but the behavior is implementation-
defined at best; as I said in another thread, see section 6.3.2.3.
Furthermore, if the implementation happens to have sizeof(int) >
sizeof(double), then the behavior is undefined. Initially t has
indeterminate value (see section 6.5.7); assigning to t.d will not
affect the bytes of t.i that aren't part of t.d. So the evaluation
of *ip in this case accesses bytes that are still indeterminate and
hence causes undefined behavior (see section 3.16).
Quote:
> I can understand that code like the following may not necessarily work,
> but the union above, I personally think should. Non-working code:
> int f(void) {
> double d = 3.0;
> int *ip = (int *)&d;
> return *ip;
> }
Indeed, this code contains an additional problem in that &d may not be
correctly aligned for conversion to int * and hence "the resulting
pointer might not be valid" (section 6.3.4), causing undefined behavior
when it's used. This is not an issue for unions because section 6.5.2.1
guarantees that pointers to their members are interconvertible and hence
that the members are correctly aligned for such a conversion.
If the pointer is valid in this version of the code, then the behavior
is still implementation-defined and possibly undefined for the reasons
explained under the other version.
--
Mark Brader | "[This computation] assumed that everything
Toronto | would work, a happy state of affairs found
My text in this article is in the public domain.
--