Why this union's size is 2 with bitfields?

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

    There is a paragraph in the standard that states there shall be no padding before the first member of a struct. But it does not say explicitly so about unions. The difference in size could come because it wants to align the union at 2 byte boundaries, but as it cannot pad before the first member of a struct, the struct will have one byte aligning. Also note that an union could have more members with different types, which could widen the required alignment of your union. There could be reasons for the compiler to give them at least 2 bytes alignment, for example to ease code that has to handle according the required aligment of an union.

    Anyway, there is no requirement that your union should be one byte exactly. It just has to have place for all its members.

    Here is what the C standard has to say about your second question:

    The operand of the unary & operator shall be either a function designator or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

    So your best bet is to use your way using the int. you may put braces around the code, so the temporary variable is kept local:

    void func(void) { struct bits f; { int x; scanf("%d", &x); f.bitfield = x; } /* ... */ }
    

提交回复
热议问题