Jun 3, 2016

C Programming #60: Unions

C Programming #59: Endianness

This article will try to cover the concept of Unions in C Programming language. Syntactically Unions and Structure are similar. Unions allow different type of data to be stored in same memory location.

Say we want to store a charecter, integer and float using unions. Then the prototype/definition of such a union can be done as follows.

union union_var_tag {
   char c;
   int i;
   float f;

Above definition will only give the blue print of the variable. To declare a variable of type union_var_tag can be done as follows

union union_var_tag v;

Now v is variable of type union_var_tag, which is a union with 3 member variable c, i and f. Similaryly how in structure we could get away with using union everytime there is a declaration of a variable; similar method of typedef can be applied here. Same prototype can be done using type def as follows.

typedef union union_var_tag {
   char c;
   int i;
   float f;
union_var_t v;

Just like structure we can access the member variable like v.c, v.i, v.f so on. To understand the difference between structure and union with respect to memory allocation lets a stucture which also has same member variable as union_var_t. Following C Program explains the memory layout of a union.

#include <stdio.h>

typedef union union_var_tag {
   char c;
   int i;
   float f;

typedef struct struct_var_tag {
   char c;
   int i;
   float f;

int main() 
   union_var_t union_v;
   struct_var_t struct_v;

   printf("Sizeof of union_v is %d\n", sizeof(union_v));
   printf("Sizeof of struct_v is %d\n", sizeof(struct_v));

   printf("Address of union_v is %p\n", &union_v);
   printf("Address of union_v.c is %p\n", &union_v.c);
   printf("Address of union_v.i is %p\n", &union_v.i);
   printf("Address of union_v.f is %p\n", &union_v.f);

   printf("Address of struct_v is %p\n", &struct_v);
   printf("Address of struct_v.c is %p\n", &struct_v.c);
   printf("Address of struct_v.i is %p\n", &struct_v.i);
   printf("Address of struct_v.f is %p\n", &struct_v.f);


Output of the above C Program is as follows.

Sizeof of union_v is 4
Sizeof of struct_v is 12
Address of union_v is 0x7fff490326d0
Address of union_v.c is 0x7fff490326d0
Address of union_v.i is 0x7fff490326d0
Address of union_v.f is 0x7fff490326d0
Address of struct_v is 0x7fff490326e0
Address of struct_v.c is 0x7fff490326e0
Address of struct_v.i is 0x7fff490326e4
Address of struct_v.f is 0x7fff490326e8

As we can see here in union_v all the structure members shared same address, while in case of struct_v they all have different memory allocated to them. sizeof a union is the size of highest sizeof the member variable in that union.

No comments :

Post a Comment