C Union

C Union

A union is a special data type available in C that allows to store different data
types in the same memory location. You can define a union with many
members, but only one member can contain a value at any given time. Unions
provide an efficient way of using the same memory location for multiple-purpose.

Union Defination:

To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type
with more than one member for your program. The format of the union

Advantages Of Unio

1.It occupies less memory because it occupies the memory of largest member only.

Disadvantages

It can store data in one member only.

Syntax Union :

union union_name   
{  
    data_type member1;  
    data_type member2;  
    .  
    .  
    data_type memeberN;  
};  

Example :

#include <stdio.h>
#include <string.h>
union employee    
{   int id;    
    char name[50];    
}e1;  //declaring e1 variable for union  
int main( )  
{  
   //store first employee information  
   e1.id=101;  
   strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
   //printing first employee information  
   printf( "employee 1 id : %d\n", e1.id);  
   printf( "employee 1 name : %s\n", e1.name);  
   return 0;  
}  

Accessing Union Members:

To access any member of a union, we use the member access operator (.).
The member access operator is coded as a period between the union variable
name and the union member that we wish to access. You would use the

Example:

#include <stdio.h>
#include <string.h>
 
union Data {
   int i;
   float f;
   char str[20];
};
 
int main( ) {

   union Data data;        

   data.i = 10;
   data.f = 220.5;
   strcpy( data.str, "C Programming");

   printf( "data.i : %d\n", data.i);
   printf( "data.f : %f\n", data.f);
   printf( "data.str : %s\n", data.str);

   return 0;
}



                    << PREVIEW >>



                    <<  NEXt   >>

Comments