Re: Unions Redux



On Mar 14, 6:10 pm, "Old Wolf" <oldw...@xxxxxxxxxxxxxx> wrote:
Ok, we've had two long and haphazard threads about unions recently,
and I still don't feel any closer to certainty about what is permitted
and what isn't. The other thread topics were "Real Life Unions"
and "union {unsigned char u[10]; ...} ".

Here's a concrete example:

#include <stdio.h>

int main(void)
{
union { int s; unsigned int us; } u;

u.us = 50;
printf("%d\n", u.s);
return 0;
}

Is this program well-defined (printing 50), implementation-defined, or
UB ?

Note that the aliasing rules in C99 6.5 are not violated here -- it is
not forbidden under that section to access an object of some type T
with an lvalue expression whose type is the signed or unsigned
version of T.

In other words, is there anything other than the aliasing rules that
restrict 'free' use of unions?

C89: undefined.
It is undefined because the member of the union accessed is not the
member last stored, this is explicitly stated in the Standard.

C99: well-defined.
In C99 the aliasing rules and representation requirements determine
the legitimacy in this case. As you noted, your example does not
violate the aliasing rules so you are good there. The Standard
explicitly states that the set of non-negative values common to any
given signed integer type and its corresponding unsigned type have the
same representations in both types so you are good there as well.

Robert Gamble

.



Relevant Pages

  • Re: Unions Redux
    ... The other thread topics were "Real Life Unions" ... union {int s; unsigned int us;} u; ... Note that the aliasing rules in C99 6.5 are not violated here -- it is ... It is undefined because the member of the union accessed is not the ...
    (comp.lang.c)
  • Unions Redux
    ... Ok, we've had two long and haphazard threads about unions recently, ... The other thread topics were "Real Life Unions" ... union {int s; unsigned int us;} u; ... Note that the aliasing rules in C99 6.5 are not violated here -- it is ...
    (comp.lang.c)
  • Re: properly using unions.
    ... I want to save up some space by using unions. ... typedef struct svarrec { ... short int dtype; /* These 4 bytes also accessed as int using asint ... char spare; ...
    (comp.lang.c)
  • Re: Consideration on pointer declarations
    ... expecially complex ones with embedded typedef'd unions. ... typedef struct ... int serial_number; ...
    (comp.lang.c)
  • Re: Consideration on pointer declarations
    ... expecially complex ones with embedded typedef'd unions. ... typedef struct ... int serial_number; ...
    (comp.lang.c)