Search code examples
c++endianness

Do I need to care about endianness when creating c++ program?


I know that i should care about this when reading data from binary files and with networking but what with a source code? Does it matter for endianness if I assign value, for example int = 42? Will it compile on big endian machine with big endian ordering and then not work properly on little endian machine? Or compiler will take care of this?


Solution

  • Despite its reputation as a low-level language, when writing C++ code, you are not actually writing code for a concrete computer.

    Instead, C++ code targets something called the C++ Abstract Machine, and it's the compiler's job to convert the behavior your program would cause on that Abstract Machine into a something (technically anything) that causes the same effect on the actual targeted machine.

    In practice, most compilers bypass this and convert code semi-directly to the final target, but that's still the model they have to respect.

    Endianness, amongst other things that we take for granted, is not a concept that exists within the C++ abstract machine. Unless you delve into working with raw data, as you pointed out, you don't have to worry about it.

    As an extreme-ish example, take >>, the bit-shift operator. It has a well-defined behavior on the abstract machine for multi-byte types, so its behavior cannot depend on the endianness of the target. It's not the actual bits that are bit-shifted, it's the value.