Skip to content

Module 7 · Structures, Unions, Enums and typedef — topic 2 of 4

Unions

A union stores different types in the same memory, one at a time. Learn how unions differ from structures, how to use a tag to track the active member, and where unions are genuinely useful.

Beginner 12 min read·Lesson 28 of 37 in C Programming

Learning objectives

  • Explain how a union's members share memory
  • Compare sizeof for a struct and a union with the same members
  • Build a tagged union to store one of several types safely

Definition

A union is a user-defined type whose members all begin at the same address and overlap in storage; its size is at least that of its largest member, and at most one member holds a meaningful value at any time.

Introduction

A structure reserves space for all of its members. A union reserves space for the largest one only, and every member uses that same space. Writing one member overwrites the others.

That sounds limiting, but it is exactly right when a value can be one of several kinds — a token that is either a number or an operator, or a configuration value that is an int, a float or a string.

Why it matters

Unions appear in compilers, interpreters, network protocols and embedded code where memory is tight or data has variant forms.

“Difference between structure and union” is one of the most frequently asked C viva questions.

Detailed explanation

Syntax mirrors struct: union Value { int i; double d; char s[8]; };. sizeof(union Value) is at least 8 (the largest member), plus any alignment padding.

Only the member you last wrote is meaningful. C allows reading a different member (type punning); the bytes are reinterpreted, which is implementation-specific and best avoided in portable code.

A tagged union pairs a union with an enum (the tag) inside a struct. The tag records which member is active, and code switches on it before reading.

structunion
Storageseparate for each membershared by all members
Size≥ sum of members (+ padding)≥ largest member (+ padding)
Members valid at onceallone
Typical userecordsvariants, memory saving

Syntax

C
union Number {
int i;
float f;
};
union Number n;
n.i = 42; /* i is active */
n.f = 3.5f; /* now f is active; i is overwritten */
struct Tagged {
enum { INT, FLOAT } kind;
union { int i; float f; } as;
};
  • Initialise a union with braces; the first member is set unless you use a designator ({.f = 1.0f}).
  • Access members with . and -> as for structs.
  • Always know which member is active.

Code examples

Struct vs union size

C
#include <stdio.h>
struct S { int i; double d; char c; };
union U { int i; double d; char c; };
int main(void) {
printf("struct: %zu bytes\n", sizeof(struct S));
printf("union: %zu bytes\n", sizeof(union U));
return 0;
}
Output
struct: 24 bytes
union:  8 bytes

The struct needs room for all three members plus padding; the union only for the 8-byte double.

Writing one member overwrites another

C
#include <stdio.h>
union Data {
int number;
char text[4];
};
int main(void) {
union Data d;
d.number = 0;
d.text[0] = 'A';
d.text[1] = '\0';
printf("text = %s\n", d.text);
d.number = 66; /* overwrites the first bytes of text */
printf("number = %d\n", d.number);
return 0;
}
Output
text = A
number = 66

More examples

A tagged union for mixed values

C
#include <stdio.h>
typedef enum { V_INT, V_REAL, V_TEXT } Kind;
typedef struct {
Kind kind;
union {
int i;
double r;
const char *t;
} as;
} Value;
void print_value(Value v) {
switch (v.kind) {
case V_INT: printf("int %d\n", v.as.i); break;
case V_REAL: printf("real %.3f\n", v.as.r); break;
case V_TEXT: printf("text \"%s\"\n", v.as.t); break;
}
}
int main(void) {
Value row[] = {
{V_INT, {.i = 42}},
{V_REAL, {.r = 3.14159}},
{V_TEXT, {.t = "hello"}},
};
for (int i = 0; i < 3; i++) print_value(row[i]);
printf("sizeof(Value) = %zu\n", sizeof(Value));
return 0;
}
Output
int  42
real 3.142
text "hello"
sizeof(Value) = 16

Step-by-step explanation

  • Kind names the three possible types; it is the tag.
  • The anonymous union as holds one of int, double or const char * in 8 shared bytes.
  • Designated initialisers ({.r = 3.14159}) choose which union member to set.
  • print_value switches on the tag, so it always reads the member that was written.
  • The whole Value is 16 bytes on a 64-bit system: 4 for the tag, 4 of padding, and 8 for the union.

Expected output

Running “A tagged union for mixed values” prints exactly:

TextOutput
int 42
real 3.142
text "hello"
sizeof(Value) = 16

Practical applications

  • Interpreters (Lua, CPython internals) store values as tagged unions.
  • Network code uses unions to view the same bytes as fields or as a raw buffer.
  • Compilers represent syntax-tree nodes of different kinds with tagged unions.

Best practices

  • Wrap unions in a struct with a tag and switch on it.
  • Use unions to model “one of” data, structs for “all of” data.
  • Avoid type punning through unions in portable code; use memcpy to reinterpret bytes.

Common mistakes

Reading the wrong member

Avoid

union Number n;
n.f = 1.5f;
printf("%d\n", n.i);

Prefer

union Number n;
n.f = 1.5f;
printf("%f\n", n.f);

n.i reinterprets the float's bits as an integer (1069547520 on IEEE systems), not 1.

Expecting all members to keep their values

Avoid

u.i = 5;
u.d = 2.0;
printf("%d\n", u.i); /* not 5 */

Prefer

struct { int i; double d; } s = {5, 2.0};
printf("%d\n", s.i);

If you need every field at once, you need a struct, not a union.

Important notes

  • Exact sizes depend on alignment rules; 24 and 16 bytes above are typical for 64-bit desktop compilers.
  • C11 anonymous unions let you write v.i instead of v.as.i when the union has no name.

Key takeaways

  • Union members share the same memory; only one is valid at a time.
  • A union's size is about the size of its largest member.
  • Track the active member with an enum tag.

Try it yourself

  1. 1
    Create a tagged union Shape holding either a circle (radius) or a rectangle (width, height) and write a function that returns its area.
  2. 2
    Print the size of a union containing char, short and long long and explain it.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

3 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is the size of a union compared with its members?
  • ModerateWhat is printed?
  • AdvancedOn a little-endian machine, after `union { uint32_t u; uint8_t b[4]; } x; x.u = 0x11223344;`, what is `x.b[0]`?
Practise this topic