C Programming Unions

Last modified by Microchip on 2023/11/09 09:07

What are 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 a Union

Syntax

union unionName
{
type1 memberName1;

typen memberNamen;
}

Back to top

Example

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

Back to top

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 and union allows the same memory location to be viewed and manipulated as different data types.

Back to top

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

Back to top

Creating a Union With typedef

Syntax

typedef union unionTagoptional
{
type1 memberName1;

typen memberNamen;
} typeName;

Back to top

Example

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

Back to top

Unions Memory Storage

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

Back to top

Examples

Unions

Unions2

Unions3

Unions4

Back to top

Example From Typical .h File

Union Final

Back to top