# Differentiate Between Struct and Union. When is Union Preferred Over Struct? Give on Example of Each. - Structured Programming Approach

Distinguish Between

Differentiate between struct and union. When is union preferred over struct? Give on example of each.

#### Solution

 Sr. No. Structure Union 1 Memory allotted to structure is equal to the space require collectively by all the members of the structure. Memory allotted for a union is equal to the space required by the largest memory of that union 2 Data is more secured in structure. Data can be corrupted in a union. 3 Structure provide ease of programming. Unions are comparatively difficult for programming. 4 Structures require more memory. Unions require less memory. 5 Structure must be used when information of all the member elements of a structure are to be stored. Unions must be used when only one of the member elements of the union is to be stored.

1. Union is preferred over struct when only one of the member elements of the union is stored.
Example of structure: #include
#include
Struct student
{
char name[20];
int roll_no;
float fees;
};
void main()
{
Struct student s1;
clrscr();
printf(“Enter the student’s name, roll number ”);
gets(s1.name);
scanf(“%d”,&s1.roll_no);
printf(“The student details are as follows: \nName:%s\n
Roll number:%d”,s1.name,s1.roll_no);
getch();
}

 Output:Enter the student’s name, roll number:John20The student details are as follows:Name:JohnRoll number:20

Example of union:
#include
#include
Union info
{
char name[20];
};
void main()
{
Union info i1;
int choice;
clrscr();
scanf(“%s”,i1.name);
getch();
}

Concept: Structure
Is there an error in this question or solution?