How to know that which variable from Union is Used?

后端 未结 6 973
北荒
北荒 2021-02-01 22:32

If I declare a Union as:

union TestUnion
{
    struct 
    {
      unsigned int Num;
      unsigned char Name[5];
    }TestStruct;
    unsigned char Total[7];
};         


        
6条回答
  •  情话喂你
    2021-02-01 22:56

    The member to use is the one you last wrote to; the other(s) are off limits. You know which member you last wrote to, don't you? After all, it was you who wrote the program :-)


    As for you secondary question: the compiler is allowed to insert 'padding bytes' in the structure to avoid unaligned accesses and make it more performant.

    example of a possible distribution of bytes inside your structure
    
    Num    |Name     |pad
    - - - -|- - - - -|x x x
    0 1 2 3|4 5 6 7 8|9 a b
    

提交回复
热议问题