Simple Union Example in C
On this page (10sections)
About this program
This is an example program in c structure and union programs. Read the concept first: C Structures, then study the code and output below.
Definition
- A union is like a struct, but all members share the same memory location.
- Only one member can hold a valid value at a time.
- Unions are useful for saving memory or representing data that can be one of several types.
Syntax
union tag_name {
type member1;
type member2;
};
Simple Union Example Program
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main(void) {
union Data data;
data.i = 10;
printf("data.i = %d\n", data.i);
data.f = 3.14f;
printf("data.f = %.2f\n", data.f);
/* After writing f, i is no longer valid */
return 0;
}
Sample Output
data.i = 10
data.f = 3.14
Union vs Structure
| Feature | Structure | Union |
|---|---|---|
| Memory | Each member has its own space | All members share one space |
| Size | Sum of members (with padding) | Size of largest member |
| Usage | Store all fields together | Store one field at a time |
Practical Example — Integer or Float
#include <stdio.h>
union Value {
int asInt;
float asFloat;
};
int main(void) {
union Value v;
v.asInt = 42;
printf("As integer: %d\n", v.asInt);
v.asFloat = 3.5f;
printf("As float: %.1f\n", v.asFloat);
return 0;
}
Sample Output
As integer: 42
As float: 3.5
Detailed About Union Concepts
See the full tutorial: C Unions.
Related Pages
Learn the concept first, then study the code:
- C Programs — Browse all C Programs.
- C Structures — Concept — struct declaration and member access.
- Simple Structure Example Program — More in c structure and union programs.