Lesson 5 of 6 · Strings, Structs and Files · 3 min read · Updated
Unions
A type whose members share one piece of memory — how it differs from a struct, and when it is useful.
A union is written like a struct, but all its members live in the same memory. It is only as big as its largest member, and it holds one member's value at a time: storing into one member overwrites the others.
#include <stdio.h>
struct S { int i; float f; char c; };
union U { int i; float f; char c; };
int main(void)
{
printf("struct size: %zu\n", sizeof(struct S));
printf("union size: %zu\n", sizeof(union U));
union U u;
u.i = 65;
printf("u.i = %d\n", u.i);
u.c = 'Z'; /* overwrites the same memory */
printf("u.c = %c\n", u.c);
return 0;
}
struct size: 12
union size: 4
u.i = 65
u.c = Z
Warning
Read only the member you last stored. After u.c = 'Z', reading u.i gives a value that depends on the machine — the bytes of 'Z' mixed with what was left of 65. The union does not remember which member is current; you must.
The usual pattern: a union inside a struct
#include <stdio.h>
#include <string.h>
enum Kind { CASH, UPI };
struct Payment {
enum Kind kind; /* which member of data is in use */
union {
int rupees;
char upi_id[20];
} data;
};
int main(void)
{
struct Payment p[2];
p[0].kind = CASH;
p[0].data.rupees = 500;
p[1].kind = UPI;
strcpy(p[1].data.upi_id, "priya@upi");
for (int i = 0; i < 2; i++) {
if (p[i].kind == CASH) {
printf("Cash: Rs %d\n", p[i].data.rupees);
} else {
printf("UPI: %s\n", p[i].data.upi_id);
}
}
return 0;
}
Cash: Rs 500
UPI: priya@upi
A payment is either cash or UPI, never both, so a union saves the space of the unused one. The kind field — an enum, a set of named constants — records which member is valid, and every reader checks it first. This "tagged union" is how unions are used in real code.
A union has members int a;, double b; (8 bytes) and char c;. How big is it at least?
Try this now
- Print
sizeoffor a struct and a union with the same memberschar name[20]; int id;and explain the difference. - Add a third payment kind, CARD, with a 4-digit card ending, to the Payment example.
- Write a union that holds either a mark (int) or a grade (char), with a tag, for 3 students.
Create a free account to save your progress, or sign in.