C++ union Keyword
Example
Store values in a union, one at a time:
union Data {
int myNum;
char myLetter;
};
int main() {
Data myData;
myData.myNum = 15;
cout << myData.myNum << "\n";
myData.myLetter = 'A';
cout << myData.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 store a value in one member, the values of the other members are lost. Only read the member that you stored a value in last.
Unions are used to save memory, for example in programs for small devices. In most programs, a struct is a better choice.
Related Pages
The struct keyword defines a structure, where each member has its own memory.
Read more about structures in our C++ Structures Tutorial.