Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz

Article

Codzify - Union in C Language

4 min 13 sec read

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.

Recommended Articles

Did you found this article helpful?

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor