C Programming Unions
Last modified by Microchip on 2023/11/09 09:07
Contents
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;
}
{
type1 memberName1;
…
typen memberNamen;
}
Example
1
2
3
4
5
6
7
2
3
4
5
6
7
// Union of char, int and float
union mixedBag
{
char a;
int b;
float c;
}
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 and 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
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
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;
{
type1 memberName1;
…
typen memberNamen;
} typeName;
Example
1
2
3
4
5
6
7
2
3
4
5
6
7
// Union of char, int and float
typedef union
{
char a;
int b;
float c;
} mixedBag;
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 accommodate the union's largest member.