What is a union?

前端 未结 5 2023
轮回少年
轮回少年 2021-02-08 09:58

Recently I am working on windows and I found that lot of data structures are defined as struct with union as member variables. Example of this would be

5条回答
  •  臣服心动
    2021-02-08 11:00

    Imagine you have a struct which holds a packet of data. The data in the packet can be of a few different types, so you store the type in a member called type. So to read the data in this packet, you first check the type, then you read the corresponding data member, which should contain the data in the packet.

    Without unions the data struct would look like this:

    struct data {
        type_t type;
    
        int number;
        char * string;
        double fraction;
        long long big_number;
    }
    

    This would be a rather big data structure. It uses enough room to store one of every possible data type. That's a little unnecessary when you will definitely only have one of those members containing useful information at any point in time.

    If we use unions:

    struct data {
        type_t type;
    
        union payload {
             int number;
             char * string;
             double fraction;
             long long big_number;
        }
    }
    

    Then the struct contains only enough space to store the type plus one of the payload members (i.e. you will have allocated an amount of memory equal to the size of type_t plus the size of the largest possible payload member). This saves a load of space and is much more efficient.

    You do have to be careful however, because if the payload contains an int, you can still read it as a double. You will probably just get extremely strange numbers as your program tries to interpret the data wrongly

提交回复
热议问题