×
☰ Menu

Accessing Union Members

We use the member access operator (.) to go to any union member.


The member access operator is a period between the name of the union variable and the name of the union member we want to access.  To define variables of the union type, you'd use the term union.

 

The following example demonstrates how to incorporate unions into a program:

#include <stdio.h>
#include <string.h>
 
union Uni {
   int i;
   float f;
   char str[20];
};
 
int main( ) {
   union Uni data1;        
   data1.i = 20;
   printf( "data.i : %d\n", data1.i);
   
   data1.f = 10.5;
   printf( "data.f : %f\n", data1.f);
   
      strcpy( data1.str, "C Language");
   printf( "data.str : %s\n", data1.str);
   
   return 0;
}

 

Output: 

data1.i : 20
data1.f : 10.500000
data1.str : C Language

--------------------------------
Process exited after 1.06 seconds with return value 0
Press any key to continue . . .