CHAPTER 14

image

Union

The union type is identical to the struct type, except that all fields share the same memory position. Therefore, the size of a union is the size of the largest field it contains. In the following code this is the integer field, which is 4 bytes large.

union mix {  char c;  /* 1 byte */  short s; /* 2 bytes */  int i;   /* 4 bytes */};

Given this memory sharing, the union type can only be used to store one value at a time, because changing one field will overwrite the value of the others.

int main(void) {  union mix m;  m.c = 0xFF; /* set first 8 bits */  m.s = 0;    /* reset first 16 bits */}

The benefit of a union, in addition ...

Get C Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.