C Union

A union is like a structure, but all its members share the same memory. So only one member can hold a valid value at a time. The size of a union is the size of its biggest member.

Example

#include <stdio.h>

union Data {
    int i;
    float f;
    char text[8];
};

int main(void) {
    union Data d;

    d.i = 25;
    printf("i = %d\n", d.i);

    d.f = 3.5f;                 // overwrites the same memory
    printf("f = %.1f\n", d.f);
    return 0;
}

Output:

Output of the above program is

i = 25
f = 3.5

After d.f is stored, the value of d.i is not valid any more.

Union vs structure size

#include <stdio.h>

struct S { int i; float f; char text[8]; };
union  U { int i; float f; char text[8]; };

int main(void) {
    printf("struct: %zu bytes\n", sizeof(struct S));
    printf("union : %zu bytes\n", sizeof(union U));
    return 0;
}

Output:

Output of the above program is

struct: 16 bytes
union : 8 bytes

Difference

PointStructureUnion
MemoryEach member has its own memoryAll members share one memory
SizeSum of all members (plus padding)Size of the biggest member
ValuesAll members can hold values togetherOnly one member at a time
Keywordstructunion

Where is a union useful?

  • When memory is very small (embedded systems).
  • To read the same data in different ways, for example, as an int or as 4 bytes.
  • To store a value that can be of different types, together with a variable which tells the current type.
Note: If you read a member different from the last one written, the result is not reliable. Keep track of which member is in use.

Next: C typedef.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.