Re: FAQ-Question



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.

Robert Gamble

.



Relevant Pages

  • Re: How to escape the Ocamls superfluous parentheses and type declarations?
    ... > This expression has type char but is here used with type int ... > Anyway, I'll define the union explicitly, so I can continue onward: ... > Unbound value quit ...
    (comp.lang.ml)
  • Re: Whats the output
    ... int i:5; ... and char in bitwise manner int will store 5 bit and char will store 2 ... However when i'll use union the output is 4.which is not clear to ...
    (comp.lang.c)
  • Re: Application of Union in C
    ... is to use a `union` with a `char` array: ... Reading out values of `b` is always OK, as `char` cannot have ... It's much better to use unsigned char rather than char (which can be ... storing a value in one member of a union and then reading ...
    (comp.lang.c)
  • Re: how to cast from (void*) to other types?
    ... > DR> type (string or unsigned int)" ... > With best regards, Roman Mashak. ... char parameter; ... Having it be a union has a few virtues ...
    (comp.lang.c)
  • Re: Unions, storage, ABIs
    ... > char Char; ... first address of the union. ... member. ... Even when compiled with a different compiler you could ...
    (comp.lang.c)