Skip to main content

Overview of Unions in C

What is Union

A union is a user-defined data type that allows a programmer to define a data structure that can hold different data types in the same memory location.

Union Syntax

Following is the syntax of Union:

union union_name {
type1 member1;
type2 member2;
type3 member3;
//...
};

Explanation

  • union_name is the name of the union
  • member1, member2, member3, and so on are the members of the union
  • Each member can be of different data types.

Example of Union

#include <stdio.h>
#include <string.h>

union person
{
char name[50];
int age;
float salary;
};

int main()
{
union person p;

strcpy(p.name, "John"); // set the value of the name member
printf("Name: %s\n", p.name);

p.age = 25; // set the value of the age member
printf("Age: %d\n", p.age);

p.salary = 2500.50; // set the value of the salary member
printf("Salary: %f\n", p.salary);

return 0;
}
Output:

Explanation

  • We define a union person that has three members: name, age, and salary.
  • We create a union variable p and set the value of each member in turn.
  • Because only one member of the union can hold a value at any given time, the value of the previously set member is overwritten when a new member is set.

Properties of union

The union data type in C has the following properties:

Memory allocation

  • When a union variable is declared, the compiler allocates enough memory to hold the largest member of the union.
  • The union can hold only one member at a time, but the value of the union can be changed to any of its members.
  • This means that all members of a union share the same memory location.

Size

  • The size of a union is equal to the size of its largest member.
  • For example: if a union has a member of type int and another member of type char, the size of the union will be equal to the size of an int.

Member access

  • The members of a union can be accessed in the same way as the members of a structure, using the dot notation.
  • However, only one member of a union can be accessed at any given time.

Data conversion

  • Union variables can be typecast to any member type.
  • This means that the data stored in a union can be interpreted as any of its members, regardless of the original type of the data.

Initialization

  • A union variable can be initialized with a value of any of its members.
  • For example: if a union has a member of type int and another member of type float, it can be initialized with an integer value or a float value.

Aliasing

  • Because all members of a union share the same memory location, modifying one member of a union can change the value of another member.
  • This can lead to unpredictable behavior and is known as "aliasing".