1: //union.cpp
3: #include <iostream>
4: using namespace std;
6: int main()
7: {
8: cout << "\nThis program illustrates the C/C++ concept of a \"union\".";
9: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
11: cout << "\nWe begin by declaring a union with three fields: int, "
12: "double, and char.";
13: union SampleUnion
14: {
15: int i;
16: double d;
17: char c;
18: };
19: SampleUnion u;
20: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
22: u.i = 65;
23: cout << "\nThen we first put an integer into this union.";
24: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
25: cout << "\nNow we output the value as an integer: " << u.i;
26: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
27: cout << "\nThen we output the value as a double: " << u.d;
28: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
29: cout << "\nFinally, we output the value as a char: " << u.c;
30: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
32: u.d = 3.14159;
33: cout << "\nSecond, we put a double into the union.";
34: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
35: cout << "\nThen we output the value as an integer: " << u.i;
36: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
37: cout << "\nThen we output the value as a double: " << u.d;
38: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
39: cout << "\nFinally, we output the value as a char: " << u.c;
40: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
42: u.c = 'z';
43: cout << "\nThird, we put a character into the union.";
44: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
45: cout << "\nThen we output the value as an integer: " << u.i;
46: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
47: cout << "\nThen we output the value as a double: " << u.d;
48: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
49: cout << "\nFinally, we output the value as a char: " << u.c;
50: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
51: }