Re: FAQ-Question
- From: "Robert Gamble" <rgamble99@xxxxxxxxx>
- Date: 20 Jun 2006 19:43:16 -0700
Dann Corbit wrote:
"Robert Gamble" <rgamble99@xxxxxxxxx> wrote in message
news:1150830838.825729.67580@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Dann Corbit wrote:
"Till Crueger" <TillFC@xxxxxxx> wrote in message
news:pan.2006.06.20.18.53.22.108909@xxxxxxxxxx
Hi,
I stumbled upon the following code to determine byte ordering in the
FAQ:
union {
int i;
char c[sizeof(int)];
} x;
/* do stuff */
In this case it seems that the union was used to convert a memory
section
from int to char[]. However I've learned that you couldn't use unions
to
reinterpret a memory area, because you can't always be sure that the
fields realy do use the same positions. So why is this code portable?
From : ISO/IEC 9899:1999 (E) (which is the current standard) we have
this:
5 One special guarantee is made in order to simplify the use of unions:
if a
union contains several structures that share a common initial sequence
(see
below), and if the union object currently contains one of these
structures,
it is permitted to inspect the common initial part of any of them
anywhere
that a declaration of the complete type of the union is visible. Two
structures share a common initial sequence if corresponding members have
compatible types (and, for bit-fields, the same widths) for a sequence of
one or more initial members.
That does not have any bearing on the presented example though as there
are no structures involved.
Rather astounding.
If you say so.
That would mean that this is perfectly fine:
#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("%d\n", (unsigned)bar.aa.carr[0]);
return 0;
}
I don't think so. aa and bb do not "share a common initial sequence"
as aa.carr and bb.ui are not compatible types so the exception rule
once again does not apply.
Robert Gamble
.
- References:
- FAQ-Question
- From: Till Crueger
- Re: FAQ-Question
- From: Dann Corbit
- Re: FAQ-Question
- From: Robert Gamble
- Re: FAQ-Question
- From: Dann Corbit
- FAQ-Question
- Prev by Date: Re: Bit field arrays unsupported?
- Next by Date: Re: FAQ-Question
- Previous by thread: Re: FAQ-Question
- Next by thread: Re: FAQ-Question
- Index(es):
Relevant Pages
|