user2711115
user2711115

Reputation: 457

Is this C99 IS_LITTLE_ENDIAN macro portable?

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

Answers (1)

Bathsheba
Bathsheba

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_ENDIANness.

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

Related Questions