C union Keyword
Example
Create a union and use one member at a time:
union myUnion {
int myNum;
char myLetter;
};
int main() {
union myUnion u1;
u1.myNum = 15;
printf("%d\n", u1.myNum);
u1.myLetter = 'A';
printf("%c", u1.myLetter);
return 0;
}
Definition and Usage
The union keyword defines a union. A union is like a structure, but all its members share the same memory.
This means that a union can only hold one value at a time. When you give a value to one member, the other members no longer hold valid values.
Use a union when you need to store one of several types, and want to save memory. The size of a union is at least the size of its largest member.
Related Pages
The struct keyword defines a structure, where each member has its own memory.
Read more about unions in our C Unions Tutorial.