Union in C – free C programming tutorial

In this tutorial, union available in C programming language that is explained in easier manner along with the syntax of defining a variable , accessing data members and example illustrating defining a variable & accessing of all the data members.

UNION :

Union is also like structure, i.e. it is defined as collection of different data types which are grouped together under a common variable name.
Each data element in a union is called member.
The only difference from the structure is in the allocation of memory for their members.
Structure allocates storage space for each member randomly at different locations. Whereas, Union allocates one common storage space for all its members.
i.e. We can use it search for a particular data in a record or a set of records.

Syntax of defining union:

union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};

#union is a keyword, which is used to represent a union.
var_name1 , var_name2 , var_name3 are data elements which are known as members.

Example of defining :

union student
{
int id;
char name[10];
char address[50];
};

Initializing and Declaring a variable :

For accessing we have to create a variable (i.e. data) of data-type student.

union student data;
union student data = {001,”AKKI”, ”mumbai”};

Accessing data members :

To access each data elements or member, we have to use dot operator(.)

data.id;
data.name;
data.address;

Example of C program which illustrates declaring and accessing of union in C :

#include < stdio.h >
#include < conio.h >
struct student
{
 char name[30], sex;
 int rollno;
 float percentage;
};
union details
{
  struct student st;
};
void main()
{
  union details set;
  printf("Enter details:");
  printf("\nEnter name : ");
  scanf("%s", set.st.name);
  printf("Enter roll no : ");
  scanf("%d", &set.st.rollno);
  printf("Enter sex : ");
  scanf("%c", &set.st.sex);
  printf("Enter percentage :");
  scanf("%f", &set.st.percentage);

  printf("\nThe student details are : \n");
  printf("\name : %s", set.st.name);
  printf("\nRollno : %d", set.st.rollno);
  printf("\nSex : %c", set.st.sex);
  printf("\nPercentage : %f", set.st.percentage);
}

When the above is compiled and executed successfully, the result given below is obtained.

OUTPUT :

Enter details
Enter name : Aayushi kumawat
Enter roll no : 1104
Enter sex : F
Enter percentage : 91.5

The student details are : 
Name : Aayushi kumawat
Roll no : 1104
Sex : F
Percentage : 91.5

This is all about the basics of union available in C programming language which is explained in easier manner along the syntax of defining a variable , accessing data members and example illustrating defining a variable & accessing of all the data members.

If you have any query please comment bellow.

Leave a Comment

Your email address will not be published. Required fields are marked *