Union: Accessing Union Members & Nesting in C

To access union members we can use dot operator (.) between union variable and union member name as follows:

<Union-Variable-Name>.<MemberAddress>

For example, to access marks of union student we can do as follows:

union student std2;

std2.marks = 20;

Now, the data member percentage of union student also contains the same value 20 but in floating point format. As soon as, the other data member of union is assigned some value, the marks member is overwritten with that. Also, two variables of same union type can be used on two sides of an assignment operator.

union_var1 = union_var2;

As a Structure definition can contain other Structure variables as members, so can Union. This is called Nesting of Union. In addition, we can use dot operator to access nested union and use dot operator again to access variables of nested union as is in case of structures. However it should be noted that a union definition can’t contain the variable of its own type as a data member. The program 1 shows how union variable behaves which is followed by the screenshot of the output.

#include <stdio.h>
union student
{
int rno;
char name[50];
}
std;
void main()
{
printf(“\n\t Enter student roll no: “);
scanf(“%d”, &std.rno);
printf(“\n\n\t Enter student name : “);
scanf(“%s”, std.name);
printf(“\n\n Student roll no : %d”,
std.rno);
printf(“\n\n Student name : %s”,
std.name);
}

Program 1: Program to show usage and working of union

Screenshot from 2020-07-20 22-40-10