union除了用于节省空间,还有一些其他用法。

1. 省去位操作 bit masking / bit shifting

typedef union {
  struct {
    unsigned char byte1;
    unsigned char byte2;
    unsigned char byte3;
    unsigned char byte4;
  } bytes;
  unsigned int dword;
} HWRegister;
...
HWRegister reg;
reg.dword = 0x12345678;
reg.bytes.byte3 = 4;
typedef union {
  struct {
    unsigned char b1:1;
    unsigned char b2:1;
    unsigned char b3:1;
    unsigned char b4:1;
    unsigned char reserved:4;
  } bits;
  unsigned char byte;
} HWRegister;
...
HWRegister reg;
reg.byte = 0;
reg.bits.b2 = 1;

2. 模拟OO里的对象继承和多态

typedef enum { TYPE1, TYPE2, TYPE3 } Type;

typedef int Derived1;
typedef char* Derived2;
typedef struct {
  int i;
  double d;
} Derived3;

typedef struct {
  Type type;
  union {
    Derived1 d1;
    Derived2 d2;
    Derived3 d3;
  };
} Base;

void do_something(Base* p) {
  switch(p->type) {
  case TYPE1:  // do something with p->d1
    break;
  case TYPE2:  // do something with p->d2
    break;
  case TYPE3:  // do something with p->d3
    break;
  }
}

3. 避免强制类型转换

例子:如何判断机器的endianness