Unions


So far we have looked at structures and typedefs as examples of user-defined types. There are still more user-defined types to examine. The one we will examine next is the union. A union allows you to handle an area of memory that could contain different types of variables. The syntax for unions is identical to that for structures. You can even contain unions within structures, or vice versa. The following is an example of a union data type.

union NumericType   // Declare a union that can hold                  // the following: { intiValue;      // int value long   lValue;  // long value double dValue;  // double value };

If you think about it, the reason these data types are called unions is that they are the union of several different data types. The following is an example using a union.

Example 8.6

Step 1: Enter the following code into your favorite text editor.

#include <iostream> using namespace std;   union NumericType   // Declare a union that can                  // hold the following: {    intiValue;      // int value    long   lValue;  // long value    double dValue;  // double value }; int main() {  NumericType values;  cout << "Please enter a number \n";  cin >> values.dValue;  cout << "Please enter another number \n";  cin >> values.lValue;  cout << values.dValue;  cout << " \n";  cout << values.lValue;        cout << "press any key to continue\n";            return 0;    }

Step 2: Compile your code.

Step 3: Run your code. You should see something similar to Figure 8.5.

click to expand
Figure 8.5: Using a union.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net