
  
C and C++
Main page
Defines
Design
Loops
Pointers
Punctuation
Strings
Stuctures
Types
SITE SERVICES
Contact Us
Search
Site Map
|
Home —» C and C++ —» structures —» unions
C Tutorial: Unions
Defining Unions:
A union is the equivalent of an assembler org or a COBOL REDEFINE. It 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 use either typedef's or instream definitions: simply replace the word struct with the word union.
You can contain unions within structures, or structures within unions. Either way, the C union is an unwieldy mechanism. In C++ unions were modified to make them easier to use. In C++ only you can use anonymous unions.
For an alternative way of dealing with redefined areas, see the section called Void Pointers in the Pointer tutorial. In that section, a record is read into a character buffer and then a pointer to a structure describing the particular record layout is loaded with the buffer address using an appropriate cast.
A union might be used to group different record layouts from the same file, or to handle a single field that could contain, for example, either numeric or character data.
typedef struct transaction
{
int amount;
union
{
int count;
char name[4];
} udata;
char discount;
} Transaction;
The fields in this structure are referred to as follows:
Transaction trans;
trans.amount = 0;
trans.udata.count = 0;
trans.discount = 'N';
Just as in any other language, it's up to you to determine what kind of variable is present in any instance. If you do arithmetic on a character string, you'll probably S0C7 abend.
Using Structures within Unions:
Unions can contain any types of variables, including structures. Be aware that the length of a union is the length of its longest variable. If the name in the previous example had only been 3 characters long, there would have been an undefined slack byte after name, since an integer occupies 4 bytes.
If you have a more complex situation than a simple redefine of one scalar variable with another, you may need to use structures in the union. Let's say an area in the record could contain either one long integer or two short integers; one solution would be to define a structure for the two shorts.
typedef struct twoshorts
{
short smallamount1;
short smallamount2;
} TwoShorts;
typedef union udata
{
TwoShorts smallamounts;
int bigamount;
} Udata;
|