Here is a common trick used to detect endianness at runtime, seen for instance in the C FAQ:
int x = 1;
if (*(char *)&x == 1)
{
/* little-endian */
}
else
{
/* big-endian */
}
According to my reading of the standard, it does not lead to an undefined behavior since it does not break the strict aliasing rule.
Anyway, as long as an integer type other than unsigned char can contain padding bits (such as x), couldn’t the condition *(char *)x == 1 be wrong even if it is a little-endian system?
In that case, is the solution with unions better for doing this?
I’m not sure endianness really makes sense when you have padding bits, but the otherwise you are right and the condition might be wrong. At least you are not invoking undefined behavior as character types have no trap representations.
Otherwise what you can do is to use exact-width integer types (like
uint32_t, etc.). Although these types are optional, they are guaranteed to have no padding bits.For information, note that
signed charalso cannot have padding bits.