Unions allow a variable to hold objects of different types in the same memory location. All members of a union share the same memory location, which is the size of the largest member. This means unions save memory by storing all members in one block, but the programmer must ensure the correct member is being accessed based on the data currently stored. The example program defines a union called Student containing different data types, reads values into members, and displays the members to demonstrate unions share the same memory location.
• A unionis declared using the keyword union as:
union student
{
char name[20];
int roll_no;
float marks;
char section;
};
union student s;
• While accessing union members, we should make sure that
we are accessing the member whose value is currently
residing in the memory. Otherwise we will get erroneous
output (which is machine dependent).
2
3.
Unions:
• A unionis a variable that may hold (at different
times) objects of different types and sizes, with the
compiler keeping track of size and alignment
requirements.
• Unions provide a way to manipulate different kinds
of data in a single area of storage, without
embedding any machine-dependent information in
the program.
• Both structure and unions are used to group a
number of different variables together.
Syntactically both structure and unions are exactly
same. The main difference between them is in
storage.
• In structures, each member has its own memory
location but all members of union use the same
memory location which is equal to the greatest
member’s size.
3
4.
Example: program illustratesthe structure in which read member elements of union and display
them.
#include<stdio.h>
union Student
{
char name[20];
int roll;
char sec;
F loat marks;
};
union Student s1;
void main()
{
printf(“Enter the name of a student”);
gets(s1.name);
printf(“Enter the roll number of a student”);
scanf(“%d”,&s1.roll);
printf(“Enter the section of a student”);
scanf(“%c”,&s1.sec);
printf(“Enter the marks obtained by the student”);
scanf(“%f”,&s1.marks);
/displaying the records
printf(“Name=%sn Roll number =%dn Section=%cn Obtained marks=%f”,s1.name,
s1.roll, s1.sec, s1.marks);
}
4