Michael Veksler <[EMAIL PROTECTED]> writes: | So, is union is a very useful feature in ISO C, without | gcc's extension? It seems that the only legal use of union | is to use the same type through the whole life of the object. | | Here is the rationale: | | Quoting Richard Guenther <[EMAIL PROTECTED]>: | > On 1/25/06, Alexandre Oliva <[EMAIL PROTECTED]> wrote: | > > On Jan 22, 2006, Richard Guenther <[EMAIL PROTECTED]> wrote: | > > | [...] | > > | > > > int ii; double dd; void foo (int *ip, double *dp) { | > > > *ip = 15; ii = *ip; *dp = 1.5; dd = *dp; } | > > > void test (void) { union { int i; double d; } u; | > > > foo (&u.i, &u.d); } | > > | > > So it is perfectly valid, but if GCC reorders the read from *ip past | > > the store to *dp, it turns the valid program into one that misbehaves. | > | > *ip = 15; ii = *ip; *dp = 1.5; dd = *dp; | > Here ^^^ | > you are accessing memory of type integer as type double. And gcc will | > happily reorder the read from *ip with the store to *dp based on TBAA | > unless it inlines the function and applies the "special" gcc rules about | > unions. | > So this example is invalid, too. | | So in theory, if there is a union of two non-char types: | union { T1 v1, T2 v2} x; | it is illegal to access both x.v1 and x.v2 for the same variable x | anywhere in the whole program.
I don't see anything in the ISO C standard that implies that. This x.v1 = 384; x.v2 = 94.08; int v = x.v2; x.v1 = v; is valid fragment. -- Gaby