Bitfields, why implementation specific?

荒凉一梦 提交于 2019-12-01 14:21:35

问题


C/C++ bitfields seem to have a lot of application in hardware drivers and binary network transfers. However they don't seem to be widely used and are generally discouraged, because the actual binary layout is implementation specific, as seen in this quote from the C99 standard 6.7.2.1/10 - "Structure and union specifiers";

An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.

My question is rather simple; Why did the committee decide to leave bit fields to be something implementation specific, and thereby making it a compiler construct, which can mainly be used for reduced memory usage, where's it could in many cases have been used to provide nice binary layouts, and free developers from bit-fiddling code?


回答1:


For the same reason so many other things are not strictly specified by the standard: To allow flexibility to produce a compliant compiler for a large number of platforms and systems, and still have an EFFICIENT compiler.

In particular, bitfields having to be stored in a particular bit/byte-order would make it horribly slow on machines whose natural byte-order is the "wrong way around".

Yes, it means that it's a right pain in the behind to make bitfields portable across multiple archiectures and platforms. If you really need that, then perhaps you should consider some other solution...



来源:https://stackoverflow.com/questions/17723604/bitfields-why-implementation-specific

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!