Friday, July 29, 2016

C Basics - Union in C

Union is a special derived data type in C. It allows storing different data types in the same memory location.

Union is defined using union element. The format of the union statement is,

union [union tag] {

   member definition;   
   ...
   member definition;
} [one or more union variables];

Union tag and variable fields are optional. Member definition is a normal variable definition.

union employee {
   char  name[50];
   int   age;
   int   emp_id;
} bob;

In above example, there are 3 members in the variable bob. The size(sizeof(bob)) of variable is 50 bytes.

The memory occupied by a union will be large enough to hold the largest member of the union.

The keyword union is used to define variables of union type. Union members are accessed using member access operator(.). Union holds the final value assigned to its member.

#include <stdio.h>
#include <string.h>

union employee {
   char  name[50];
   int   age;
   int   emp_id;
} ;
 
int main( ) {

   union employee bob;        
   
   bob.age = 43;
   printf( "bob.age : %d\n", bob.age);
   
   bob.emp_id = 20160715;
   printf( "bob.emp_id : %d\n", bob.emp_id);
   
   strcpy( bob.name, "Bob Restler");   
   printf( "bob.name : %s\n", bob.name);

   printf( "bob.age : %d\n", bob.age);
   printf( "bob.emp_id : %d\n", bob.emp_id);
   printf( "bob.name : %s\n", bob.name);

   return 0;
}
The output of the above program would be:

bob.age : 43
bob.emp_id : 20160715
bob.name : Bob Restler
bob.age : 543321922
bob.emp_id : 543321922
bob.name : Bob Restler



Related topics:
Structures in C   |   Structures and Function Parameters in C   |   Structures and Pointers in C   |   Structure Bit Fields in C   |   Enumeration in C   |   Typedef in C

List of topics: C Programming

No comments:

Post a Comment