union的常见用法

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

posted on   chenkkkabc  阅读(445)  评论(0编辑  收藏  举报
< 2013年3月 >
24 25 26 27 28 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6

点击右上角即可分享
微信分享提示