Bit fields portability

前端 未结 3 951
悲哀的现实
悲哀的现实 2020-12-20 13:28

I read here that bit fields are not portable. Does that mean that the code below that defines bit fields (code taken from here) could not compile on certain machines?

<
3条回答
  •  抹茶落季
    2020-12-20 14:20

    Bit fields are standard language feature. They will compile in all C compilers. They are portable in that sense of the term. Your code is well-formed and will compile in all C compilers as well.

    Statements like "bit-fields are not portable" usually mean that the physical layout of bit-fields in memory might differ from implementation to implementation (i.e. from one compiler to another). You might get different output from your program, if compiled on different implementations. But the the difference in program's behavior can only occur if (and when) your code depends on the memory layout of objects with bit-fields (e.g. if you measure their size, as you do in your program).

    In other words, to say that "bit-fields are not portable" is pretty much the same thing as to say that type int is "not portable" just because it can have different size on different platforms or use different endianness in its internal representation.

提交回复
热议问题