Introduction of Unions in C

 

Unions

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

Defining a Union

union [union tag] {

   member definition;

   member definition;

   ...

} [one or more union variables];  


Get the total memory size used by the Union

#include <stdio.h>

#include <string.h>

union Data {
  int i;
  float f;
  char str[20];
};

int main() {
  union Data data;
  printf("Memory size occupied by data : %d\n", sizeof(data));
  return 0;
}

Output:-

Memory size occupied by data : 20


Accessing Union Members 

You can do this by using the member access operator (.)

#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;
}

Output :- 

data.i : 1917853763

data.f : 4122360580327794860452759994368.000000

data.str : C Programming

(You can see that the variable of i and f member of Union got corrupted)


Lets see the same example where we use the one variable of member at a time then move to next declaration variable of member

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

   union Data data;        

   data.i = 10;
   printf( "data.i : %d\n", data.i);
   
   data.f = 220.5;
   printf( "data.f : %f\n", data.f);
   
   strcpy( data.str, "C Programming");
   printf( "data.str : %s\n", data.str);

   return 0;
}

Output:- 

data.i : 10

data.f : 220.500000

data.str : C Programming






0 Comments