To access union members we can use dot operator (.) between union variable and union member name as follows:
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.
printf(“\n\t Enter student roll no: “);
printf(“\n\n\t Enter student name : “);
printf(“\n\n Student roll no : %d”,
printf(“\n\n Student name : %s”,
Program 1: Program to show usage and working of union
For any query or issue, feel free to discuss on http://discuss.eduguru.in