Unions in C
This article provides in-depth information on Unions in C programming language. It explains what Unions are, how they are defined, how to access their members, how to determine the size of a union and also provides examples of unions in C. The article also highlights the key difference between Unions and Structs in C.
Unions in C are a type of data structure that allows the storage of multiple variables of different data types in the same memory location. Unions offer a practical means of serving several purposes with the same memory space. They allow access to the same memory location as different data types, which can be useful to save memory or manipulate values in different ways.
In this tutorial, we will go in-depth into the implementation of Unions in C. So, without further ado, let’s get started!
We will be covering the following sections:
- C Union
- Defining a Union in C
- Accessing Union Members
- Determining the Size of a Union
- Examples of Union in C
- Difference Between Structs and Union in C
C Union
In C programming language, there is a special user-defined data type called union that allows variables of different data types to be stored in the same memory location. A union can be defined with multiple members, but only one of those members can contain a value at a given time.
Let’s look at the following example:
union iPhone
{
char model[50];
int price;
};
As you can see, we use the union keyword to define unions. The above code defines a derived type: union iPhone.
The C union is similar to Structs in C [insert link here] except for one key difference – C Structures allocate enough space to store all members at the same time, whereas unions can hold only one member’s value at a particular point in time.
Also explore: C Programming Online Courses & Certifications
Best-suited C / C++ courses for you
Learn C / C++ with these high-rated online courses
Defining a Union in C
The syntax of the union statement in C is given below:
union union_tag { datatype member1; datatype member2; ... datatype memberN;} [one or more union variables];
When we define a union, a user-defined type gets created. However, no memory is allocated as of now. In order to allocate memory to a given union type, we create variables.
Let’s examine the following brief illustration:
union iPhone{ char model[50]; int price;} iPhone12, iPhone13, *iPhone14;
Here, we have created union variables iPhone12, iPhone13, and a union pointer iPhone14 of union iPhone type.
Also read:14 Most Important Features of C Language
Also explore: C Programming Online Courses & Certifications
Explore free C++ courses
Accessing Union Members
We use the (.) operator to access members of a union. In the above example though, we also have a pointer variable. To access that, we use also the (->) operator. So,
- price for variable iPhone12, we use iPhone12.price
- price using pointer variable iPhone14, we can use either (*iPhone14).price or iPhone14->price
Let’s look at one more example for a better understanding of how unions work:
#include <stdio.h>union employee { float experience; int empCode;} emp;
int main() { emp.experience = 4.3;
// when emp.empCode is assigned a value // emp.experience will no longer hold 4.3 emp.empCode = 100;
printf("Experice: %.1f\n", emp.experience); printf("Employee Code = %d", emp.empCode); return 0;}
Output:
Experice: 0.0
Employee code: 100
In the above example, the union employee has a member experience that is assigned 4.3 in value. But, when the union member empCode is assigned a value as well, the value of member experience becomes 0.0 because union members share the memory location. So, unions can contain only one member value at one time
Determining the Size of a Union
The size of a C Union is based on the size of the largest member of that union.
Let’s understand this through an example:
#include <stdio.h>union letter{ int a; char b; float c; double d; };
int main() { printf("The size of union letter is %d", sizeof(union letter)); return 0; }
Output:
We already know that the size of:
- int data type is 4
- char data type is 1
- float data type is 4
- double data type is 8
Since the double variable d requires the largest memory space among the four variables, a total of 8 bytes is allocated in the memory for the union letter.
Examples of Unions in C
Example 1:
#include <stdio.h>
union Data { int i; float f;};
int main() { union Data data;
data.i = 10; printf("data.i : %d\n", data.i);
data.f = 220.5; printf("data.f : %f\n", data.f);
return 0;}
Output 1:
In this example, the union Data has two members: an integer “i” and a floating-point number “f”. The union variable data can hold either an integer or a floating-point number, depending on which member is assigned a value. In the above program, first an integer value is assigned to “data.i” and then a floating-point value is assigned to “data.f”. When the values are printed, only the value of the last assigned member is displayed.
Example 2:
#include <stdio.h>
union student { int id; float marks; char grade;};
int main() { union student record;
record.id = 101; printf("Student ID: %d\n", record.id);
record.marks = 85.5; printf("Student Marks: %f\n", record.marks);
record.grade = 'A'; printf("Student Grade: %c\n", record.grade);
return 0;}
Output 2:
Student ID: 101
Student Marks: 85.500000
Student Grade: A
In this example, a union student has three members: an integer “id”, a floating-point number “marks”, and a character “grade”. The union variable record can hold either an integer or a floating-point number or a character, depending on which member is assigned a value. Here, first an integer value is assigned to “record.id”, then a floating-point value is assigned to “record.marks”, and finally a character value is assigned to “record.grade”. When the values are printed, only the value of the last assigned member is displayed.
Differences Between Structs and Unions in C
Features | Struct | Union |
Memory Allocation | Each member has their own memory location | All members share the same memory location |
Size | Sum of sizes of all members | Size of the largest member |
Usage | Store related data | Save memory by sharing memory location |
Initialization | Members can be initialized individually | Only the first member can be initialized |
Accessing Members | Dot (.) operator | Dot (.) or arrow (->) operator |
Endnotes
Hope this article helped you grasp the concept of unions in C. Unions provide a way to save memory space by reusing the same memory location for multiple variables of different data types.
Explore our C articles to find out more about the language and consolidate your knowledge of the fundamentals.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio