Why this union's size is 2 with bitfields?

前端 未结 6 1239
独厮守ぢ
独厮守ぢ 2021-01-06 15:14

I am working on turbo C on windows where char takes one byte.Now my problem is with the below union.

union a
{
 unsigned char c:2;
}b;
void main()
{
printf(\         


        
6条回答
  •  隐瞒了意图╮
    2021-01-06 16:03

    In addition to the fact that there "there may also be unnamed padding at the end of a structure or union", the compiler is permitted to place a bitfield in "any addressable storage unit large enough to hold a bit-field". (both quotes are from the C90 standard - there is similar, but different, wording tin the C99 standard).

    Also note that the standard says that a "bit-field shall have a type that is a qualified or unqualified version of int, unsigned int, or signed int", so having a bit-field in a char type is non-standard.

    Because the behavior of bitfields are so dependent on unspecified compiler implementation details (there are several other non-portable issues with bit-fields that I have not mentioned) using them is almost always a bad idea. In particular, they are a bad idea when you are trying to model bit-fields in a file format, network protocol, or hardware register.


    More information from another SO answer:

    In general you should avoid bitfields and use other manifest constants (enums or whatever) with explicit bit masking and shifting to access the 'sub-fields' in a field.

    Here's one reason why bitfields should be avoided - they aren't very portable between compilers even for the same platform. from the C99 standard (there's similar wording in the C90 standard):

    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.

    You cannot guarantee whether a bit field will 'span' an int boundary or not and you can't specify whether a bitfield starts at the low-end of the int or the high end of the int (this is independant of whether the processor is big-endian or little-endian).

提交回复
热议问题