What is Union In C Language?

What is Union in C?



·      Union is nothing but a user define data type which is get used to store different types of elements in it.
·      Union is like structure which serve same purpose but the difference is that at once only one member of the union can occupy memory.
·      Which means size of the union in any instance is equal to the size of its largest element.
·      Ex:-           
 


Structure                                                                           Union

Struct Student                                                                  union Student
{                                                                                         {                      
Char name;            // Size 1 byte                                     char name;     // Size 1 byte
Int   roll_no;         //  Size 2 byte                                     Int   roll_no;      //  Size 2 byte
Float marks;          // Size   4 bytes                                  Float marks;     // Size   4 bytes
}student;   // Size  7 bytes                                               }student;          // Size  4  bytes

Size of student is = 1+2+4 = 7 bytes                            Size of student is = 4 (Maximum size of 1 element)


·      Union is used to save memory space so when we wanted to use less memory for our program at that time union will occupy less memory space once we use it whereas Structure takes more memory space.
·      Problem with union is that it stores last entered data in union when we stored new value at that time it overwrites the new value on old one in union.

·      Syntax to Define Union:-
union union_name  
    data_type member1; 
    data_type member2; 
    -----//----------;
    -----//--------;
    data_type memeberN; 
}; 

·      Example to define union:-
union  student 
{   int roll_no; 
    char name[50]; 
    float percentage; 
}; 

·      Program which implement Union :-

#include <stdio.h> 
#include <string.h> 
union  student 
{   int roll_no; 
    char name[50]; 
    float percentage; 
}std;                                          //declaring std variable for union 
void main( ) 
   //store first student information 
   std.roll_no=1; 
   strcpy(std.name, "Ganesh");   //copying string into char array 
   //printing first student information 
   printf( "student 1 roll_no : %d \n", std.roll_no); 
   printf( "student 1 name : %s\n", std.name);


·      Output:-
Student 1 roll_no         : 1869508435
Student 1 name     : Ganesh


·      In above output we can see that roll no has got garbage value is because last value was entered was name of student which overwrites the roll_no data. So that’s why we will only see name value of student.

Comments

Popular Posts