Jens said:
One way to test for endianess is to use a union:
Is there any particular reason you want to use a union for such a
purpose? Casting any data pointer to unsigned char is the way mandated
by the standard to inspect individual bytes of an object.
Where is this mandated? 6.2.6.1p4 includes:
exactly
Use of a union with a [preferably 'unsigned'] 'char' (signed
considerations discussed elsethread) array which exactly overlaps some
other member appears to accomplish precisely the same thing
(inspection). The original post referred to a strategy offered in a C
FAQ, if I recall correctly.
Because in appendix J, J.1 unspecific behavior it lists:
- The value of a union member other than the last one stored into
So the standard clearly says that pointers to unsigned char are ok and
that for unions the implementation may decide to throw you some other
values in the face. And this is even "unspecific behavior" and not
"implementation defined", so an implementation is not even obliged to
document this or to be consistent with it.
Apparently you have a misunderstanding of the nature of the two
kinds of statements in the Standard.
All statements made in Annex J are 'informative', which means
they do not define the language but just are reflective of
other statements (called 'normative') that officially state
the actual requirements. The statements in Annex J are given
as useful summaries, but they are approximate, not exact,
statements of actual requirements.
The particular entry in this subparagraph of J.1 gives a
reference to 6.2.6.1. The relevant text for this case is
in 6.2.6.1p7, which says:
When a value is stored in a member of an object of union
type, the bytes of the object representation that do not
correspond to that member but do correspond to other members
take unspecified values.
It is only the bytes of other members _that do not correspond
to the member being stored_ that take on unspecified values.
When it happens, as it does in the upthread example, that all
member objects in the union overlap exactly, other members do
_not_ taken on unspecified values but are exactly determined by
the byte values actually stored and the (implementation-defined)
representations of the types in question.
Unions are guaranteed to work in this way for this kind of
access. As long as the byte being accessed corresponds to
a byte of the member object last stored into, its contents
must be exactly the same as the byte of the object representation
that was stored.