How to know that which variable from Union is Used?

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

    Another example of including the union with an enum to determine what is stored. I found it much more clear and to the point.

    from: https://www.cs.uic.edu/~jbell/CourseNotes/C_Programming/Structures.html

    author: Dr. John T. Bell


    In order to know which union field is actually stored, unions are often nested inside of structs, with an enumerated type indicating what is actually stored there. For example:

    typedef struct Flight {
        enum { PASSENGER, CARGO } type;
        union {
            int npassengers;
            double tonnages;  // Units are not necessarily tons.
        } cargo;
    } Flight;
    
    Flight flights[ 1000 ];
    
    flights[ 42 ].type = PASSENGER;
    flights[ 42 ].cargo.npassengers = 150;
    
    flights[ 20 ].type = CARGO;
    flights[ 20 ].cargo.tonnages = 356.78;
    

提交回复
热议问题