What is a union?

前端 未结 5 2012
轮回少年
轮回少年 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 10:53

    When a struct contains union members it's generally done as a space saving mechanism. If the struct can be of certain sub-types by which only certain members are valid then a union is a good way to not waste space.

    For example

    enum NumberKind {
      Integer, 
      FloatingPoint 
    };
    
    struct Number {
      NumberKind kind;
      union {
        int integerValue;
        float floatValue;
      };
    };
    

    In this scenario I've defined a struct Number which can have type types of numeric values: floating point and integer. It's not valid to have both at the same time so rather than waste space by having both members always defined I created a union which makes the storage of both equal to the size of the biggest.

    Sample Usage of Above as requested

    void PrintNumber(Number value) {
      if (value.kind == Integer) {
        printf("%d\n", value.integerValue);
      } else {
        printf("%f\n", value.floatValue);
      }
    }
    

提交回复
热议问题