Safe use of unions
- From: dingoatemydonut@xxxxxxx
- Date: 30 Jun 2006 07:55:27 -0700
The quoted text below is from comp.std.c which originated
from a discussion on comp.lang.c. I've edited out the parts
that do not apply to my question.
Robert Gamble wrote:
Dann Corbit wrote:
#include <stdio.h>
int main(void)
{
typedef union foo_u {
struct a {
unsigned char carr[sizeof(unsigned int)];
} aa;
struct b {
unsigned int ui;
} bb;
} foo;
foo bar;
bar.bb.ui = 1;
printf("%u\n", (unsigned)bar.aa.carr[0]);
return 0;
}
#include <stdio.h>
int main(void)
{
typedef union foo_u {
unsigned char carr[sizeof(unsigned int)];
unsigned int ui;
} foo;
foo bar;
bar.ui = 1;
printf("%u\n", (unsigned)bar.carr[0]);
return 0;
}
Is the first sample safe but the second not safe?
Neither are safe.
Why is either example unsafe? I understand the output of
the printf calls is unspecified. But I do not see anything
that would be cause for concern other than that.
.
- Follow-Ups:
- Re: Safe use of unions
- From: Jack Klein
- Re: Safe use of unions
- Prev by Date: Re: OT: Windows console programs (was Re: Function Pointers)
- Next by Date: Re: void vs void* (philosophical question)
- Previous by thread: new/delete
- Next by thread: Re: Safe use of unions
- Index(es):
Relevant Pages
|