← Back to C Course | Chapter 8: Structures & Unions | Lesson 5 of 7

C Unions

What is a Union?

This shared-memory design makes unions much more memory-efficient than structures when you only ever need one of several possible values at a time -- for example, representing a value that could be an int, a float, or a string, but never more than one simultaneously.

Example: What is a Union?

c
#include <stdio.h>
union Data {
	int i;
	float f;
};
int main() {
	union Data d;
	d.i = 5;
	printf("%d", d.i);
	return 0;
}

Defining a Union

This is syntactically identical to defining a structure, but the compiler's memory layout is fundamentally different: every member starts at the same base address rather than being laid out sequentially.

Example: Defining a Union

c
#include <stdio.h>
union Value {
	int i;
	char c;
};
int main() {
	union Value v;
	v.i = 65;
	printf("%d", v.i);
	return 0;
}

Memory Allocation in Unions

If your union has an int (4 bytes) and a double (8 bytes), the union's total size is 8 bytes -- exactly enough for its largest member, since all members overlap the same memory region rather than being stacked.

Example: Memory Allocation in Unions

c
#include <stdio.h>
union Data {
	int i;
	double d;
};
int main() {
	printf("%zu", sizeof(union Data));
	return 0;
}

Accessing Union Members

Writing to one member and then reading a different member reinterprets the same raw bytes as a different type, which is sometimes done deliberately (called 'type punning') but is usually a bug if done accidentally.

Example: Accessing Union Members

c
#include <stdio.h>
union Data {
	int i;
	float f;
};
int main() {
	union Data d;
	d.i = 10;
	d.f = 3.5f;
	printf("%.1f", d.f);
	return 0;
}

Unions vs. Structures

Choose a structure when you need to store several related values simultaneously (like a point's x and y), and a union when you need to represent one value that could be several different types depending on context (like a variant/tagged data type).

Example: Unions vs. Structures

c
#include <stdio.h>
struct Point { int x, y; };
union Value { int i; float f; };
int main() {
	struct Point p = {1, 2};
	union Value v;
	v.i = 5;
	printf("%d %d %d", p.x, p.y, v.i);
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.