Reputation: 457
While looking for a compile-time endian detection macro I found this:
#define IS_LITTLE_ENDIAN (1 == *(unsigned char *)&(const int){1})
According to an answer to C Macro definition to determine big endian or little endian machine?, this can be evaluated at compile-time (at least with GCC) and doesn't assume any memory alignment. Is this really portable (provided C99 is available) and if so what are the caveats of this macro?
Upvotes: 2
Views: 661
Reputation: 234705
There is indeed no undefined behaviour here so it's portable in that sense.
But the condition doesn't necessarily prove IS_LITTLE_ENDIAN
ness.
The storage arrangements of an int
are largely left to the implementation. There are other choices other than the classical little and big endian schemes, and your macro could yield a false positive.
Upvotes: 4