Detect entity with bits and padding bits

Here is a general trick used to determine endianness at runtime, for example in the C FAQ :

int x = 1; if (*(char *)&x == 1) { /* little-endian */ } else { /* big-endian */ } 

According to my reading of the standard, this does not lead to undefined behavior, since it does not violate the strict anti-aliasing rule.

In any case, if an integer type other than unsigned char can contain bits of additions (for example, x ), can the condition *(char *)x == 1 be satisfied, even if it is a little-individual system?

In this case, is it better to make a decision with the unions?

+4
source share
1 answer

I'm not sure that the truth makes sense when you have fill bits, but otherwise you are right, and this may be wrong. At the very least, you are not invoking undefined behavior, since character types do not have trap representations.

Otherwise, you can use integer types of exact width (e.g. uint32_t , etc.). Although these types are optional, they are guaranteed to have no fill bits.

For information, note that signed char also cannot have padding bits.

+4
source

All Articles