Codzify - Union in C Language

4 min 13 sec read Basic


The only difference between Structure and Union is structure allocates memory for every type whereas union allocates single memory for all the variables.

Union in C is a user-defined data type which allows you to store data elements of a different kind just like structures. Unions are almost the same as structures.

Difference between Structure and Union

The difference between Structure and Union in C is as follows:

 Structures                             
     |                                                  
     V                                                
 struct Student                                   
 {                                                
 char name[20];  // 1 byte                          
 int   age;      // 4 bytes                          
 } ;                                              
   
-------------------------------------------
Memory Size in Structures = 5 bytes.      

   
 Unions 
 |  
 V
 union Student
 {
 char name[20];
 int   age;         // 4 bytes 
 } ;    

-------------------------------------------
Memory in Union = 4 bytes. 
Largest among char & int is int.  

 

Unions create a single memory location and the size of that location depends on the highest size of the type described inside the union.

Here, char is of 1 byte & int is of 4 bytes.

Which one is greater? int.

So Memory Size of the union, in this case, will be 4 bytes. Whereas, In Structures, memory size will be the sum of all the types described inside structures i.e 5 bytes in our case.

How To Define Union?

The following example shows how to define union:

Syntax :-

union [union Name]
 {
  datatype variable;
  datatype variable;
  ...
  datatype variable;
 } [one or more union variables];

Example Explained

"union Name" is an "Optional" Name which is used to define union.

"datatype variable" is simply declaring a normal variable int a; float per;

"[one or more union variables]" is an "Optional" Name which is used to define one or more union variables.


Example :-

union Student
{
 char name[20]; 
 int   age;
} student; 

 

How to Access Union Members?

 

Dot Operator (.) is used to access any union member.

Following example clears the concept :-

#include 
#include 
union Students
{
    char name[20];
    int   age;
};

int main( )
{
 /* Declare firstStudent of type Students */
    union Students firstStudent;       
    
    /* firstStudent specification */
    strcpy(firstStudent.name , "Jazzy");
    firstStudent.age = 23;
    
   /* print firstStudent info */
    printf("First Student Name: %s
", firstStudent.name);
    printf("First Student age: %d
", firstStudent.age);
    
    return 0;
}

Output:-

First Student Name: Corrupted Value Dsfsmfbsmf smf smf 
First Student age: 23

Unexpected Output Right? First Student name should be Jazzy. Age = 23. But remember unions always create a single memory location consider it like a box containing Value. So we first initialized a name = Jazzy first. Then that single memory box contains Jazzy. Then we initialized age = 23. Then that single memory box contains 23 . Name value is gone now. Union variables are used one at a time. That's why First Student name value is corrupted here.

So to achieve desired output:

#include 
union Students
{
    char name[20];
    int   age;
};

int main( )
{
/* Declare firstStudent of type Students */
    union Students firstStudent;        
    
    /* firstStudent name */
    strcpy(firstStudent.name , "Jazzy");
    printf("First Student Name : %s
", firstStudent.name);

   /* print firstStudent info */
    firstStudent.age = 23;
    printf("First Student age : %d
", firstStudent.age);
    
    return 0;
}

Output:-

First Student Name: Jazzy
First Student age: 23

Unions are useful when you want to use a single memory location for multiple tasks.

Codzify's

1:1 & 1:Many Mentorship Program

Be job-ready. Learn how to crack the interviews with industry ready training program.


Learn More

Data Structures & Algorithms

What is Dynamic Programming and how to use it

This is a quick introduction to Dynamic Programming.

3 ways to check anagrams

Let's discuss the 3 ways to check anagrams and their time complexity.

Bubble Sort Algorithm

Topics covered: 1) Basics of Bubble Sort Algorithm 2) Worst Case, Best Case complexity

Introduction to Trees

What is a Tree and Terminologies like root, sibling, parent node, children, Leaf node, Ancestor & Descendant, Properties of Tree Data Structure, Depth of node, Height of node

Address Calculation in 2d array

Let's discuss about the Address Calculation using row-major order & column-major order.

Javascript

Javascript - Postfix Vs Prefix

Let's discuss the difference between postfix and prefix with a practical example.

Javascript Identifiers, Variables

In this session, we will discuss the concept of identifiers, variables and operators in javascript with a practical example.

Bootstrap

Bootstrap 4 Tutorial: Modal Popups Made Easy | Live Demo

Let's discuss the Modal Popups in Bootstrap.

How to create a dropdown list in navbar bootstrap

In this video, we will discuss How to create a dropdown list in navbar bootstrap with a practical example.

Navigation tabs in Bootstrap

Let's discuss about the navigation tabs in Bootstrap

Bootstrap Buttons

Let's discuss about the button classes in bootstrap.


Recommended tutorials