Re: Unions Redux
- From: "Robert Gamble" <rgamble99@xxxxxxxxx>
- Date: 14 Mar 2007 20:43:14 -0700
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
.
- Follow-Ups:
- Re: Unions Redux
- From: Yevgen Muntyan
- Re: Unions Redux
- References:
- Unions Redux
- From: Old Wolf
- Unions Redux
- Prev by Date: Re: Unions Redux
- Next by Date: Re: Unions Redux
- Previous by thread: Re: Unions Redux
- Next by thread: Re: Unions Redux
- Index(es):
Relevant Pages
|