This is what I offered at an interview today.
int is_little_endian(void)
{
union {
long l;
char c;
} u;
u.l = 1;
return u.c == 1;
}
My interviewer insisted that c and l are not guaranteed to begin at the same address and therefore, the union should be changed to say char c[sizeof(long)] and the return value should be changed to u.c[0] == 1.
Is it correct that members of a union might not begin at the same address?
You are correct in that the “members of a union might begin at the same address”. The relevant part of the Standard is (6.7.2.1 para 13):
Basically, a start address of the union is guaranteed to be the same as the start address of each of its members. I believe (still looking for the reference) that a
longis guaranteed to be larger than achar. If you assume this, then your solution should* be valid.* I’m still a little uncertain due to some interesting wording around the representation of integer and, in particular, signed integer types. Take a close read of 6.2.6.2 clauses 1 & 2.