Advertisement Remove all ads

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.

Advertisement Remove all ads

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:John
20
The student details are as follows:
Name:John
Roll number:20

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

Output:
Enter your name:John
Your name is John
Concept: Structure
  Is there an error in this question or solution?
Advertisement Remove all ads

APPEARS IN

Advertisement Remove all ads
Advertisement Remove all ads
Share
Notifications

View all notifications


      Forgot password?
View in app×