CodeBlanks Logo Icon CodeBlanks

union

  • C course
  • Intermediate
  • Lesson 36/116
  • 5 min

Learn to share memory between types with union.

union

A union is like a struct but all members share the same memory. So only one member is active at a time. sizeof(union) equals the size of the largest member.

Example: union Value { int i; float f; };. Here i and f share the same 4 bytes. If you write v.i = 42; then reading v.f is undefined behavior. So you must track which member is active. A union is used for memory savings; it's common in embedded systems and protocol headers.

One active member

In a union, only one member is active at a time. Writing to one member and reading another is undefined behavior; that's why tracking the active member is required.

Example: if you write union Value v; v.i = 42;, then v.i is active. printf("%f", v.f); gives an unspecified result; the bits aren't reinterpreted as a float. The right approach is to keep which type is stored in a separate variable. This pattern is called a tagged union; you'll see it in the next lesson. A union is a powerful but careful tool for memory packing.

Practice Store an int with a union and print

Define union Value with int i; and float f;. In main, write union Value v;; assign v.i = 42; and print with printf("%d\n", v.i);.

Starter code

main.c
#include <stdio.h>

// Define union Value (int i and float f)
// In main declare v, set i to 42 and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

union Value {
    int i;
    float f;
};

int main(void) {
    union Value v;
    v.i = 42;
    printf("%d\n", v.i);
    return 0;
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does sizeof(union {int a; char b;}) give?

  • sizeof(char)
  • sizeof(int) Correct answer
  • 1
  • 0

Explanation: A union's size is the size of its largest member; int is larger than char.

2 Complete the union definition

Question
union Value { int i; ____ f; };
Answer
union Value { int i; float f; };

Explanation: float is the 4-byte member added to the union.

3 Match the union expressions

Term Meaning
union Value Type definition
v.i = 42 int active
v.f = 3.14 float active
sizeof(union Value) Largest member size

All lessons in Intermediate