How to know that which variable from Union is Used?

后端 未结 6 968
北荒
北荒 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:57

    You can't. That's part of the point of unions.

    If you need to be able to tell, you can use something called a tagged union. Some languages have built-in support for these, but in C, you have to do it yourself. The idea is to include a tag along with the union which you can use to tell which version it is. Like:

    enum TestUnionTag {NUM_NAME, TOTAL};
    
    struct {
        enum TestUnionTag tag;
        union {
            struct {
                unsigned int Num;
                unsigned char Name[5];
            } TestStruct;
            unsigned char Total[7];
        } value;
    } TestUnion;
    

    Then in your code, you make sure you always set the tag to say how the union is being used.

    About the sizeof: the struct is 12 bytes because there are 4 bytes for the int (most modern compilers have a 4-byte int, the same as a long int), then three bytes of padding and five bytes for the chars (i don't know if the padding comes before or after the chars). The padding is there so that the struct is a whole number of words long, so that everything in memory stays aligned on word boundaries. Because the struct is 12 bytes long, the union has to be 12 bytes long to hold it; the union doesn't change size according to what's in it.

提交回复
热议问题