Exploring the Concept of Union in C Programming Language: Syntax, Usage and Examples

A user-defined data type, built from fundamentals like char, int, and float among other data types, and intermittently data types established based on primary data types like arrays called derived data types are documented per the use case scenarios of the software engineers.

When dealing with a multitude of variables of wide variety referring to a single common component, it might take time to grasp the semantics of the programme. The scalability and comprehension of the programme are considerably improved by the ability to process information in the programme code and to implement user-defined and customised data types.

Must Read: What is Statement in C?

Consider the following example of student details with the following descriptions.
➔ name
➔ age
➔ school name
➔ class

We can implement a multi-dimensional array to accomplish the task. Suppose an array has more than one dimension and is constituted of rows and columns. In that case, it is said to be a multi-dimensional array. A 2D array, for instance, is a collections array.

Also Read: Preprocessor Directives in C Programming Language

// We require an array to record the following data: name, age, school name, class, and date of birth. The program’s visual appearance will also resemble this.

char [100][100] student_name;
int [100] age;
//student_name[i] is Name of i-th student
// age[i] is the Age of i-th student.

char [100][100] schoolName;
char [100][100] class;
// schoolName[i] is the school name of i-th student.
// class[i] is the class of i-th students.

int [100][3] date_of_birth;
// date_of_birth[i][0] is the birthday of i-th student
// date_of_birth[i][1] is the birth month of i-th student
// date_of_birth[i][2] is the birth year of i-th student

It undoubtedly increased the algorithm’s complexity and made it more challenging to administer, especially in dynamic allocation. Therefore, adopting the user-defined data type method is more appropriate.

Also Read: How to use Storage Classes in C Language?

The methods listed below can create user-defined data types in C.

  • enumeration
  • empty data types
  • types definition
  • structure
  • union

What is a Union in C Programming Language?

A union keyword that enables the programmer to store multiple variable categories under a model within one RAM. “Members” term refers to the characteristics that come under a union.

A union and a structure are essentially identical, with the exception of members that are stored in the same programme memory. Suppose we create a union with more than one member. In that case, even then, only one is visible and available at any moment, and all members are assigned the same address.

One member can be evaluated at a time since doing so would affect the other members’ values. Thus only one data member at a time can be queried and obtained.

These are highly useful for embedded programming or when direct access to hardware or memory is required.

Advantages of Union

➢ Union consumes less memory space than structure.
➢ When utilising a union, only the largest size data member may be directly accessed.
➢ It is used when distinct data members require fewer (or the same) amounts of memory.
➢ It allocates memory to all of its data members in proportion to the size of its biggest data member.

Disadvantages of Union

➢ It only permits one data member to be accessed at a time.
➢ Union assigns a single common memory area to all of its data members, which they all share.
➢ The union data members are not entirely initialised and are utilised by exchanging values one at a time.
A union makes it simple to solve the previous case. This will be denoted by the code:

Syntax of Union in C Language

Similar to how we describe the structure, we may define the syntax of a union as being made up of members surrounded in curly brackets and a union keyword. This is how its syntax looks:

union union_name{
datatype member_1;
datatype member_2;
datatype member_3;
…..
…..
datatype member_(n-1);
datatype member_n;
};

How to Declare Union in C?

We may easily declare a union by adhering to the C language’s structure.

The variable declaration is the same as we discussed in the structure in the C programming language article for the union. To declare a union variable, we can follow either of the two. Still, method 1 is preferred when the variables needed are knowns. Otherwise, method 2 is a way to go as it provides flexibility to declare the variable numerous times.

METHOD 1: When defining a union

Here we declare the union variable at the time of structure declaration.

union student{
char name[10];
int age;
char school_name[50];
int class;
}s1, s2;

METHOD 2: Separately 

Here we declare the union variable separate from the union declaration inside the main function.

union student{
char name[10];
int age;
char school_name[50];
int class;
};

int main(){

union student s1, s2;

}

The union variables s1 and s2 can now be used to access the stored values.

How to Access Union Members in C?

To access union members, we can use the following: 

The Dot Operator

We can access members’ data using a period between the union variable name and the union member.

 s1.name;

or 

The Pointer Operator

We can access members’ data using a pointer operator between the union variable name and the union member.

   s1->name;

The following code shows the member accessing methods:

   #include <stdio.h>

#include <string.h>

union student{

char name[10];

int age;

char school_name[50];

int class;

};

int main( ) {

   union student s1;        

   strcpy( s1.name, “Kartik”);

   s1.age = 18;

   strcpy( s1.school_name, “Delhi Public School”);

   printf( “s1.name: %s\n”, s1.name);

   printf( “s1.age: %d\n”,s1.age);

   printf( “s1.school_name: %s\n”, s1.school_name);

   return 0;

}

As we can see, the preceding code compiles to the following result:

s1.name: Delhi Public School

s1.age: 1751934276

s1.school_name: Delhi Public School

Because the variable’s final value has taken the memory region, the result is tainted. As a result, the member value of the school name is successfully printed.

Let’s look at this code, which will allow us to access members individually.

#include <stdio.h>

#include <string.h>

union student{
char name[10];
int age;
char school_name[50];
int class;
};

int main( ) {

union student s1;

strcpy( s1.name, “Kartik”);
printf( “s1.name: %s\n”, s1.name);

s1.age = 18;
printf( “s1.age %d\n”, s1.age);

strcpy( s1.school_name, “Delhi Public School”);
printf( “s1.school_namer: %s\n”, s1.school_name);

return 0;
}

The output is error-free when this code is run since each member is activated only once

s1.name:Kartik

s1.age 18
s1.school_namer: Delhi Public School

What is the Use of Union in C Language?

A union is a data structure that facilitates multiple members to have a common memory location. When employing a union, the data member capable of being accessed directly is the one with the maximum length. In embedded programming, it is often implemented when direct memory accessibility is necessitated. Considering the size of its largest member, it allocates the memory size throughout its other data members.

What is the Difference Between Union and Array in C Language?

Other than their basic syntax difference, there are other differences between an array and a union, as you can see below. 

ArrayUnion
Identical data type collections of elements.A grouping of components from several data types.
The dimensions of arrays can be one or two.There is no specific type of union.
A distinct memory location is assigned to each element.The memory address shared by the elements is the same size as the largest element in the union.
At any given time, any member can have a value.A value can only be present in one member at once.
Memory is not being used effectively since each member has a different memory location assigned to them.Memory is used more effectively because no member needs dedicated memory space.
A key called an index is used to access array elements.An index cannot be used to access the components of a union.

Conclusion

Here we discuss unions in C programming in this article. A union is a form of the data structure defined by developers depending on the case using the union keyword, similar to that of a structure. And we will learn other unions related subjects, particularly union setup, member access, and distinctions between structures and unions.

Frequently Asked Questions

Q1. Explain Nested union in C language?

Ans: A nested union contains a member from another union. A union member might be the union itself, known as a nested union.

Q2. Is a union an array?

Ans: A union is a data type that allows many data types to be stored in the same memory region in the C programming language. Arrays come in both one and two dimensions. A memory address is assigned to each element the same size as the biggest element in the union.

Greetings, My name is Rumi Sadaf. I work as both a content writer and a programmer. In essence, I explain what I know and aid others in understanding programming concepts. Happy Viewing.

Leave a Comment