Union in C

Like Structures, Union in C Programming is also used to group different data types to organize the data in a structural way. A system reserved keyword union was used to create it in this programming language.

Unlike Structures, the C union variable will allocate the common memory for all of its members (i.e., age, name, address, etc.). The size of the allocated common memory is equal to the size of the largest union member. Due to this, we can save a lot of memory.

Due to this common memory, we can’t access all the union members at the same time. Because the union variable holds one member at a time, we can access one member at a time.

C Union Syntax

It is the system reserved keyword used to create and access its members. The UName is the name you want to give for this union. For example, employees, persons, and students. The basic syntax of the Union in C Programming is as shown below.

union UName
{
  Data_Type Variable_Name; //Member

  Data_Type Variable_Name; //Member

  ………….
};

Data_Type means the Data type of the variable that you want to declare. For example, int, float, char, etc. And the Variable_Name is the name of the variable. For example, id, age, name, and salary. For Example

union Student //Name = Employee

{

  //Members
  int Roll_No; //Data Type = int; Variable Name = Roll_No

  char name[50]; //Data Type = char Array; Variable Name = name

  char address[100]; //Data Type = Char Array; Variable Name = address

};

Declaration of Union in C Programming

Before accessing the members inside it, we have to create the variables. We can declare the variables in multiple ways. The First Approach is declaring the union first and then, in the main function, creating the variable.

union Employee

{

  int age;

  char name[50];

  float salary;

};

//Creating the Structure variable

 union Employee emp1, emp2;

 emp1 = {25, "Dave", 25000}

Here, emp1 and emp2 are the variables of this data type. The second approach is to create the programming variables at the time of the union declaration.

union Employee

{

  int age;

  char name[50];

  float salary;

} emp1, emp2;

Accessing Members of a Union

We can access the members of the Union in this C Programming using the dot operator (.) or members operator. For example, let us use the above example.

//Assigning the values

 emp1.age = 26;

 strcopy (emp1.name, "Michel");

 emp1.salary = 46000.50;

Union in C Programming Example

In this program, we are going to declare a union with four members. Then we will display every individual member as output in 2 different ways. Please refer Structures article in C Programming to understand the structures.

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

union Employee 
{
  int age;  
  char Name[50];
  char Department[20];
  float Salary;
};

int main() 
{
  union Employee emp1;
  union Employee emp2;
    
    emp1.age = 28;
    strcpy(emp1.Name, "Chris");
    strcpy(emp1.Department, "Science");
    emp1.Salary = 32000.70;

  printf("\nDetails of the First Employee \n");
 
  printf("  Employee Age = %d \n", emp1.age);
  printf("  Employee Name = %s \n", emp1.Name);
  printf("  Employee Department = %s \n", emp1.Department);
  printf("  Employee Salary = %.2f \n\n", emp1.Salary);

  printf("Details of the Second Employee \n" );

  emp2.age = 30;
  printf("  Employee Age = %d \n", emp2.age );
  
  strcpy(emp2.Name, "David");
  printf("  Employee Name = %s \n", emp2.Name );

  strcpy(emp2.Department, "Technology" );
  printf("  Employee Department = %s \n ", emp2.Department );

  emp2.Salary = 35000.20;
  printf("  Employee Salary = %.2f \n ", emp2.Salary );

  return 0;
}
Union in C programming

Within this C union example program, we declared the Employee with age, Name, Department, and Salary members with appropriate Data Types. Within the main() function, We created 2 variables, emp1, and emp2, for the Employee.

Details of the First Employ.

From the below statement, you can see that the variable will allocate memory for the age member. It means the value of 28 stores in the memory location for age (age = 28).

emp1.age = 28;

From the below statement, you can observe that the C Union variable has to allocate memory for the Name member. So, it will remove the data of the previous entry, i.e., age. Then it will allocate the same memory to the Name member. It means Chris will store it in a memory location (Replaced age here).

strcpy(emp1.Name, "Chris");

Now the variable has to allocate memory for the Department member. So, it will remove the data of the previous entry, i.e., Name. Then it will allocate the same memory to the Department member. It means Science is stored in a memory location (Replaced Chris here).

strcpy(emp1.Department, "Science");

Next, the C Union variable has to allocate memory for the Salary member. So, it will remove the data of the previous entry, i.e., Department, and allocate the same memory to the Salary member. It means 32000.70 stored in the memory location (Replaced Science here).

emp1.Salary = 32000.70;

The below printf statements are useful to output the values we assigned for the members. The following statement will display a wrong or strange value because other values have already replaced the age value.

printf(" Employee Age = %d \n", emp1.age);

The following statement will display a wrong or strange value because other values have already replaced the Name value.

printf(" Employee Name = %s \n", emp1.Name);

Below union statement displays strange or wrong values because the Department value has already been replaced by Salary.

printf(" Employee Department = %s \n", emp1.Department);

The following statement prints the correct Salary value. Because after this, we haven’t assigned the memory location to other values.

printf(" Employee Salary = %.2f \n", emp1.Salary);

Details of the Second Employee. The Union allows us to access one data member at a time. So in this variable, we will display the output immediately after assigning the value to that data member.

emp2.age = 30;

printf(" Employee Age = %d \n", emp2.age);

The variable will allocate memory for the age member. It means the value of 28 stores in the memory location for age (age = 28). After assigning the value, it immediately prints the output of age.

Now the C Union variable has to allocate memory for the Name member. So, it removes the data of the previous entry, i.e., age. Then it will allocate the same memory to the Name member. It means David is stored in a memory location (Replaced age here).

strcpy(emp2.Name, "David");

printf(" Employee Name = %s \n", emp2.Name);

TIP: If you forget to print the statement immediately, the data will be removed and allocated to the next member.

The process is the same for the below statements.

strcpy(emp2.Department, "Technology");
printf(" Employee Department = %s \n", emp2.Department);

emp2.Salary = 35000.20;
printf(" Employee Salary = %.2f \n\n", emp2.Salary);

TIP: Please refer to the difference between union and structure and bitwise operators articles.

Can a C union contain a pointer?

Yes. Just like any other data type, such as the integer, float, string, or array, we can use a pointer as a union member.

In the following example, we declared a union with two members: one integer variable and a pointer to store string information. Within the main program, we created a union variable and assigned the text Hello World to the declared pointer.

NOTE: If we use a union with a pointer member, it will utilize the shared memory like any other member.

#include <stdio.h>
union Sample
{
int i;
char *str;
};

int main()
{
union Sample s1;
s1.str = "Hello World!";
printf("%s\n", s1.str);

return 0;
}
Hello World!

As we all know, a union allocates shared memory to all its variables. When we use the combination of a union and a pointer, the pointer member will override the memory representation of other variables.

To demonstrate the working functionality of a C union containing a pointer member, we use the same program as the above example. By default, it considers the largest data type as the default allocated memory. Here, it considers char *str as the largest data type, and in most cases, its size is 8 bytes. So, the total memory allocated by the union is 8 bytes, and the first 4 bytes are filled with an integer data type.

  • Within the main program, we assign a value to the integer member in a union and display the output.
  • Next, we assign a default text to the pointer (string) and display the output. Once the compiler executes this step, it overrides the integer value 50, and the complete memory is allocated to this text.
  • If we try to print the value inside the union integer, member, it returns a garbage value, and the value differs based on the system (or each execution).
#include <stdio.h>
union Sample
{
int num;
char *str;
};
int main()
{
union Sample s1;
s1.num = 50;
printf("Integer: %d\n", s1.num);

s1.str = "Hello World!";
printf("String: %s\n", s1.str);

printf("Integer after storing string: %d\n", s1.num);
return 0;
}
Integer: 50
String: Hello World!
Integer after storing string: 1075331085

How to access union members using a pointer?

In C programming, we can use an arrow operator (->) to access a union member with the help of a pointer. In the example below, s->name is equivalent to (*s).name.

#include <stdio.h>

union Sample
{
int age;
char *name;
};

int main()
{
union Sample data;
union Sample *s = &data;

s->name = "David Miller";
printf("Name = %s\n", s->name);

s->age = 30;
printf("Age = %d\n", s->age);

return 0;
}
Name = David Miller
Age = 30