C – Union


[rps-include post=6557]

Union is a data type used to store different type of variables. Union is very similar to the struct but have some differences those have explained below. Union can contain int,char,float,… etc. in a single block. One union can contain single set of data at a time.

Defining Unions

Defining union is very similar to struct. We will use union statement. After union statement we will put union tag. After the tag we can put variables in curly brackets. Union tag is optional. Union variables will be automatically instantiated.

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

In this example we will define an union named MyData and a variable mydata.

union MyData { 
   int count; 
   float range; 
   char name[20]; 
};

After union definition we should also initialize some variable which is in union MyData type. We will initialize variable named mydata

union MyData mydata;

Accessing Members

In this part we will access to the union members by using the name of the union variable and the member name. We can use this method both set and get member data. We will put a point between the union variable name and union member name like below.

mydata.count = 10;

Below we can see an example where member variables data is set and get.

#include <stdio.h> 
#include <string.h> 
 
union MyData { 
   int count; 
   float range; 
   char name[20]; 
}; 
 
int main( ) { 
 
   union MyData mydata; 
 
   mydata.count = 10; 
   mydata.range = 220.5; 
   strcpy( mydata.name, "C Programming"); 
 
   printf( "mydata.count : %d\n", mydata.count); 
   printf( "mydata.range : %f\n", mydata.range); 
   printf( "mydata.name : %s\n", mydata.name); 
 
   return 0; 
}

Structures vs Unions

As stated previously struct and union have syntax similarities. But the biggest difference is struct variables holds their members in separate memory areas but all same union variables will hold same memory areas. Simply single union type will hold single data for all union variables for the same type.

[rps-include post=6557]

LEARN MORE  Linux Bash How to Define, Use Shell Variables

Leave a Comment