Academic Program

Unions

Unions

Unions are similar to structures but a union’s members all share the same memory location. In essence a union is a variable that is capable of holding different types of data at different times.

Unions:

  • May contain any number of members
  • Members may be of any data type
  • Are as large as their largest member
  • Use exactly the same syntax as structures except struct is replaced with union

Creating an Union

Syntax

union unionName
{
type1 memberName1;

typen memberNamen;
}

Example

1
2
3
4
5
6
7
// Union of char, int and float
union mixedBag
{
  char a;
  int b;
  float c;
}

Purpose of a Union

Unions are similar to structures EXCEPT that struct by itself outside of a union assigns a new memory location upon declaration

union allows the same memory location to be viewed and manipulated as different data types.

Example

1
2
3
4
5
6
7
8
9
10
11
12
union{
  int Word;
  struct
  {
    char Byte1:8;
    char Byte2:8;
  }structBytes;
}myVar;
 
myVar.Word  = 0xFFFF;           // myVar = 1111111111111111
myVar.structBytes.Byte1 = 0xF0; // myVar = 0000000011110000
myVar.structBytes.Byte2 = 0xF0; // myVar = 1111000011110000

Creating a Union with typedef

Syntax

typedef union unionTagoptional
{
type1 memberName1;

typen memberNamen;
typeName;

Example

1
2
3
4
5
6
7
// Union of char, int and float
typedef union
{
  char a;
  int b;
  float c;
} mixedBag;

Unions Memory Storage

Union variables may be declared exactly like structure variables. Memory is allocated to accomodate the union's largest member.

Examples

Unions.png
Unions2.png
Unions3.png
Unions4.png

Example from Typical .h File

UnionsFinal.png