Why this union's size is 2 with bitfields?

前端 未结 6 1240
独厮守ぢ
独厮守ぢ 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:00

    There is a lot of misinformation in the answers so I will clarify. It could be for one of 2 reasons (I am not familiar with the compiler).

    1. The bitfield storage unit is 2.

    2. Alignment is forced to word (2 byte) boundary.

    I doubt it is the first case as it is a common extension to take the bitfield storage unit as the size of the declared "base" type. In this case the type is char which always has a size of 1.

    [In standard you can only declare bitfields of type int or unsigned int and the "storage unit" in which bitfields are grouped is fixed (usually the same size as an int). Even a single bit bitfield will use one storage unit.]

    In the 2nd case it is common for C compilers to implement #pragma pack to allow control of alignment. I suspect the default packing is 2 in which case a pad byte will be added at the end of the union. The way to avoid this is to use:

    #pragma pack(1)
    

    You should also use #pragma pack() afterward to set back to the default (or even better use the push and pop arguments if supported by your compiler).

    To all the repliers who said that you must put up with what the compiler does, this is contrary to the spirit of C. You should be able to use bitfields to map to any size or bit order in situations where you have no control over it such as a file format or hardware mapping.

    Of course this is highly non-portable since different implementations have different byte orders, orders that bits are added to a bitfield storage unit (from top or bottom), storage units size, default alignment etc.

    As to your 2nd question, I can't see the problem, though I never use scanf as it is problematic.

提交回复
热议问题