Please pay attention that most of the answers here are not portable, since compilers today will evaluate those answers in compilation time (depends on the optimization) and return a specific value based on a specific endianness, while the actual machine endianness can differ. The values on which the endianness is tested, won't never reach the system memory thus the real executed code will return the same result regardless of the actual endianness.
For example, in ARM Cortex-M3 the implemented endianness will reflect in a status bit AIRCR.ENDIANNESS and compiler cannot know this value in compile time.
Compilation output for some of the answers suggested here:
https://godbolt.org/z/GJGNE2 for this answer,
https://godbolt.org/z/Yv-pyJ for this answer, and so on.
To solve it you will need to use the volatile
qualifier. Yogeesh H T
's answer is the closest one for today's real life usage, but since Christoph
suggests more comprehensive solution, a slight fix to his answer would make the answer complete, just add volatile
to the union declaration: static const volatile union
.
This would assure storing and reading from memory, which is needed to determine endianness.