Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Union?
3.
Defining a Union
3.1.
Example
4.
Create a Union Variable
4.1.
Example
5.
Accessing Union Members
5.1.
Example 
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Introduction to union

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Union is an essential topic belonging to the world of programming and coding languages. We have included all of the relevant issues to the union in this blog.

Also See, Sum of Digits in C and C Static Function.

What is Union?

A union is a unique data type in C that allows keeping particular data types in the exact memory location. You may define a union with many members, but the best member can include a value at any time. Unions provide an efficient manner of using the identical memory location for multiple-motives.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Defining a Union

To define a union, you should use the union statement in the same manner as you probably did, even as defining a structure. The union statement defines a new data kind with a couple of members in your program. The format of a union statement is as follows −

union [union tag] 
{
   member definition;
   member definition;
   ...
   member definition;
} [one or more union variables];  

The union tag is optionally available, and every member definition is a normal variable definition, which includes int i; or float f; or every other valid variable definition. You could specify one or more union variables at the end of the union's definition; however, it is optional. right here is the way you would define a union type named data having three members i, f, and str −

union Data 
{
   int i;
   float f;
   char str[20];
} 
data;  

A data type variable can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., the same memory location, can be used to store multiple types of data. Depending on your need, you may use any built-in or user-defined data types inside a union.

The memory occupied using a union may be large sufficient to keep the largest member of the union. For example, inside the above example, the data type will occupy 20 bytes of memory space because this is the most space that may be occupied using a character string. 

Example

#include <stdio.h>
#include <string.h>
union Data 
{
   int i;
   float f;
   char str[20];
}; 
int main( ) 
{
   union Data data;        
   printf( "Memory size: %d\n", sizeof(data));
   return 0;
}

Output

Memory size: 20

In this example, the instance shows the full memory size occupied by the above union.

Create a Union Variable

While a union is represented, it makes a user-defined type. However, in this situation, no memory is assigned. To assign the memory, we should build variables. In this example, the instance shows the full memory size occupied by the above union.

allow's see how we can construct variables:

Example

union student
{
	char name[50];
	int roll number;
};
int main()
{
	union student stu1, stu2, *stu3;
	return 0;
}

There is one more aspect of creating a union variable:

union student
{
	char name[50];
	int roll number;
} 
stu1, stu2, *stu3;

Accessing Union Members

To access any union member, we use the member access operator. Member access operator is coded as a duration between the union variable name and the union member we desire access. You will use the keyword union to define variables of union type.

Example 

#include <stdio.h>
Union School
{
	float percentage;
	int student_No;
} j;
int main() {
	j.percentage = 12.3;
	// when j.student_No is assigned a value,
	// j.percentage will no longer hold 12.3
	j.workerNo = 100;
	printf(“Percentage = %.1f\n”, j.pPercentage);
	printf(“Number of students= %d”, j.student_No);
	return 0;
}

Output

Percentage= 0.0
Number of Students= 100

In this example, the subsequent shows the way to use unions in a program.

Also see,  Tribonacci Series and  Short int in C Programming

FAQs

  1. Is it mandatory that the size of all elements in a union should be the same?
    No it is not mandatory
     
  2. Is the size of the union is the size of the longest element in the union?
    Yes, the Max size of the union is the size of the largest data type or the memory taken by the largest member.
     
  3. What is Union?
    Union is a user-defined datatype in the C programming language. It is a collection of variables of different data types in the same memory location. We can define a union with many members, but at a given point in time, only one member can contain a value.

Key Takeaways

In this, we learned about the union and how to define a union, create a union, and learn all things about the union.

Visit here to learn more topics related to DBMS. Ninjas, don't stop here. Check out Top 100 SQL Problems to master, usually asked questions in companies, and land your dream job. Also, try  Coding Ninjas Studio to practice numerous questions asked in many interviews.

Previous article
Introduction to Enum
Next article
Difference between structure and union in C
Live masterclass