union unionName { datatype member1 ; datatype member2 ; ---------------- };
union student { int rollno; char name[20]; int age; char gender; };
union employee
{
int empno;
char name[20];
char job[20];
int salary ;
};
union book
{
char book_title[10];
char author[10];
int price;
int total_pages;
};
union unionName { datatype member1; datatype member2; ----------------- } variablesList ;
union student { int rollno; char name[20]; int age; char gender; }
#include<stdio.h> union student { int rollno; char name[20]; int age; char gender; }; main() { union student a; printf("Enter RollNo Name Age and Gender : "); scanf("%d %s %d %c",&a.rollno,a.name,&a.age,&a.gender); printf("\nRollNo is %d",a.rollno); printf("\nName is %s",a.name); printf("\nAge is %d",a.age); printf("\nGender is %c",a.gender); }
Enter RollNo Name Age and Gender : 1333 Amit 21 M RollNo is 1333 Name is Amit Age is 21 Gender is M
#include<stdio.h> union person { char fname[20]; char lname[20]; int age; }; main() { union person a; printf("Enter fname lname and age: "); scanf("%s %s %d", a.fname, a.lname, &a.age); if(a.age>=60) printf("%s %s is Senior Citizen", a.fname, a.lname); else printf("%s %s is NOT Senior Citizen", a.fname, a.lname); }
Enter fname lname and age: Amit Jain 21 Amit Jain is NOT Senior Citizen
Structure | Union |
---|---|
The keyword struct is used to define a structure | The keyword union is used to define a union. |
When a variable is associated with a structure, the compiler allocates the memory for each member. | When a variable is associated with a union, the compiler allocates the memory by considering the size of the largest member. So, size of union is equal to the size of largest member. |
Each member within a structure is assigned unique storage area of location. | Memory allocated is shared by individual members of union. |
The address of each member will be in ascending order This indicates that memory for each member will start at different offset values. | The address is same for all the members of a union. This indicates that every member begins at the same offset value. |
Altering the value of a member will not affect other members of the structure. | Altering the value of any of the member will alter other member values. |
Individual member can be accessed at a time. | Only one member can be accessed at a time. |
Several members of a structure can initialize at once. | Only the first member of a union can be initialized. |