Programming in C: Unit IV: Structures and Union

Unions Inside Structures

with Example C Program

You must be wondering, why do we need unions? Generally, unions can be very useful when declared inside a structure. Consider an example in which you want a field of a structure to contain a string or an integer, depending on what the user specifies.

UNIONS INSIDE STRUCTURES

You must be wondering, why do we need unions? Generally, unions can be very useful when declared inside a structure. Consider an example in which you want a field of a structure to contain a string or an integer, depending on what the user specifies. The following code illustrates such a scenario.

#include <stdio.h>

struct student

{

union

{

char name [20];

int roll_no;

};

int marks;

};

int main()

{

struct student stud;

char choice;

printf("\n You can enter the name or roll number of the student");

printf("\n Do you want to enter the name (Y or N): ");

gets (choice);

if (choice=='y' || choice=='Y')

{

printf("\n Enter the name: ");

gets (stud.name);

}

else

{

printf("\n Enter the roll number: ");

scanf("%d", &stud.roll_no);

}

printf("\n Enter the marks: ");

scanf("%d", &stud.marks);

if (choice=='y' || choice=='Y')  

printf("\n Name: %s", stud.name);

else

printf("\n Roll Number: %d ", stud. roll_no);

printf("\n Marks: %d", stud.marks);

return 0;

}

Now in this code, we have a union embedded within a structure. We know, the fields of a union will share memory, so in the main program we ask the user which data he/she would like to store and depending on his/her choice the appropriate field is used.

Note

Pointing to unions, passing unions to functions, and passing pointers to unions to functions are all done in the same way as that of structures.

Programming in C: Unit IV: Structures and Union : Tag: : with Example C Program - Unions Inside Structures