×

Union Program in C

 How should a union be defined?

 In C programming, a Union is a method used to organize different data types into groups in the same way that Structures are used. We are able to make user-defined data type elements by utilizing a union.

In contrast to Structures, a C union variable will allot shared memory to all of its members (i.e., book cost, book name, Writer’s name, etc.). The allocated shared memory has a size that is equivalent to that of the biggest union member. We can save a lot of memory (RAM) because of this.

 We are unable to access every union member simultaneously due to this shared memory. The C union variable can only contain one member at a time. Therefore, we can only access one member at a time.

The union is also a grouping of many items with varying properties stored in close proximity to one another in memory. They are custom data types. The structure's components are referred to as the union's members, and the union name (like date, book, etc.) is handled as a data type.

When a union is defined, no memory is allocated. Only after the creation of its variables, memory is allocated (It is typically preceded by the keyword union). Among all of its members, the variables of union types take up the most memory space. Only one of its members may store data at once and concurrently. Using the dot (.) operator, you may access the members.

Difference between Structure and Union

  • In Structure, all the data members are stored in separate memory locations, whereas in Union, all members share the same memory location.
  • A union variable's memory usage is equal to the amount of storage space required by the largest data member of the union, as opposed to a structure variable's memory usage, which equals the total of all the memory of the structure's members.
  • Unlike a structure variable, which contains all members, a union variable can only have one active member at a time.

 Union Syntax in C:

union box
{
     	int x;
     	char y;
     	float z;
};
union box b1;

 In this syntax, we initialized a union named box, which has three data members(int, char, float). Here union is the keyword, and the box is the data type.

Among all these members, the member who is taking the most memory, the box will get the same amount of memory. This indicates that

  • int takes 2-byte memory.
  • Char takes 1-byte memory.
  • Float takes 4-byte memory.

So maximum memory which is allotted to the box will be 4 bytes.

Here b1 is the variable of box data type

 x,y, and z are the member variables.

1. Example Program for C Union:

 
#include<stdio.h>
union box
{
     	int x;
     	char y;
     	float z;
};
void main()
{
     	union box b1;
     	b1.x =3;
     	printf("\n x=%d",b1.x);
     	b1.y='c';
     	printf("\n y=%c",b1.y);
     	b1.z=3.8;
     	printf("\n z=%f",b1.z);
}

Explanation:

  • Union is the keyword, and the box is the data type.
  • b1 variable has three member variables x,y, and z.
  • The dot(.) operator is used to access member variables.
     b1.x =3;   b1.y='c';         b1.z=3.8;
  • For int data type, we use %d format specifier.
  • For char data type, we use %c format specifier.
  • For float data type, we use %f format specifier.

Program Output:

Union Program in C

2-Example for C union Program:

 
#include <stdio.h>
#include <string.h>
 
union student
{
        	char name[15];
         	int age;
        	float percentage;
};
 
int main()
{
    union student data;
 
       printf("Student data is :\n");
       strcpy(data.name, "Durgesh");
       printf("Name : %s \n", data.name);
 
        data.age=18;
       printf("Age: %d \n", data.age);
 
       data.percentage = 87.63;
       printf("Percentage : %f \n", data.percentage);
       return 0;
}

Explanation :

  • “Durgesh” is assigned to union member “data.name”. The memory location name is “data.name” and the value stored in this location is “Durgesh”.
  • Then, “18” is assigned to union member “data.age”. Now, the memory location name is changed to “data.age” with the value “18”.
  • Then, “87.63” is assigned to union member “data.percentage”. Now, the memory location name is changed to “data.percentage” with the value “87.63”.
  • In a similar manner, the name and value of each union member are periodically changed in the communal storage area.
  • As soon as values are assigned to each union member, they may be retrieved.
  • Because all members share the same memory, if we don't access them before giving values to other members, the other members will overwrite the member's name and value.
  • All union members cannot be accessed at once.

Program Output:

Union Program in C

Conclusion: So, we can say that,the union makes memory management easier. Only the most recent value submitted into the union will be available, which is the union's disadvantage. When union members don't need to be accessible at the same time, this method should be utilized.


Related Topics

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

20 minutes read.

C Program to Find Largest Number Using Dynamic Memory Allocation

This tutorial will teach us how to locate the highest number a user has ever input into a dynamically allocated memory. C Program: #include <stdio.h> #include <stdlib.h> int main ()  {   int no;   double *data_n;   printf...

1 minute read.

Segmentation Fault in C

Segmentation Fault in C In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating...

4 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Difference between Scope and Lifetime in C

In this article, we will discuss about the key differences between scope and lifetime in C, including their definitions, applications, and how they relate to one another. By the end...

8 minutes read.

Pointer in C

Pointer is a variable that is used to contain the address of another variable. We can easily create a pointer in C language. Example: int *ptr Symbol Description & (ampersand sign) Address of an operator...

1 minute read.

Long int in C

We use data type to avoid the type of data to be stored for a variable at the time of declaration.So, we can say that the variable type is known...

3 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

FIFO Example in the C Language

FIFO is an acronym that means "First In, First Out." It is a data structure handling method in which the first element is handled first, and the last element is...

3 minutes read.

Union in C

Union is a user-defined data type that is used to hold the different types of elements like structure. In union, all members share the same memory location. Syntax: union [union name] { ...

1 minute read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Heap Sort in C

In this tutorial, we will learn about heap sorting in C language, but before going to Heap sort, we have to know the concept of Complete Binary Tree. What is Complete...

8 minutes read.

GCD program of two numbers in C

GCD stands for Greatest Common Divisor, which is also known as Highest Common Factor, which can be abbreviated as HCF. Mathematically it can be defined as any two positive integers...

3 minutes read.

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 minutes read.

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

Write a program that produces different results in C and C++

In this tutorial, we'll explore several programs that, depending on whether they are developed using C or C++ compilers, will produce varying outputs. There are numerous similar programs, but we will just...

2 minutes read.

Remove an element from an array in C

A collection of objects or pieces of the same data type stored in a single memory block is known as an array. A data structure called an array is used...

3 minutes read.

memcmp() in C

Introduction: In this article we are discuss about memcmp() function in C. This function permits the person to evaluate the bytes of the two characters, as mentioned above. Depending on...

4 minutes read.

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.