How to Declare Union in C: Syntax and Examples
union using the union keyword followed by a name and a block of member variables inside braces. Each member shares the same memory location, so only one member can hold a value at a time.Syntax
A union is declared with the keyword union, followed by the union name and a block containing its members. Each member can be of different types, but they share the same memory space.
- union: keyword to declare a union
- Name: identifier for the union type
- Members: variables inside braces that share memory
union UnionName {
type1 member1;
type2 member2;
type3 member3;
};Example
This example shows how to declare a union with an integer and a float. It assigns a value to one member and prints it, then assigns a value to the other member and prints it. Notice how the value changes because both members share the same memory.
#include <stdio.h>
union Number {
int i;
float f;
};
int main() {
union Number num;
num.i = 10;
printf("num.i = %d\n", num.i);
num.f = 220.5f;
printf("num.f = %.2f\n", num.f);
// After assigning to num.f, num.i value changes
printf("num.i after assigning num.f = %d\n", num.i);
return 0;
}Common Pitfalls
One common mistake is assuming all members of a union hold their values independently. In reality, all members share the same memory, so changing one member overwrites the others. Another pitfall is not initializing the union before reading a member, which can lead to undefined behavior.
Wrong way example:
union Data {
int x;
float y;
};
union Data d;
printf("d.y = %f\n", d.y); // Reading uninitialized memberRight way example:
union Data d;
d.x = 5;
printf("d.x = %d\n", d.x);Quick Reference
- Use
unionto save memory when only one of several variables is needed at a time. - Only one member can hold a valid value at any moment.
- Accessing a member different from the last assigned one leads to unpredictable results.
- Unions can be anonymous or named.
Key Takeaways
union keyword followed by member variables inside braces.