Programs to understand Unions
Union : Union is a user-defined data type that is used to store the different type of elements.At once, only one member of the union can occupy the memory. In other words, we can say that the size of the union in any instance is equal to the size of its largest element.
Syntax :
union union_name { datatype member1; datatype member2; datatype membern; }; |
---|
Example : memory allocation of the Union D is 4 bytes i.e size of float .
union D { int i; float f; } |
---|
How we create structure variables:
Example-1 :
union ABC { char n[50]; int c.No; float s; }; void main() { union ABC a1, a2, a[20]; } |
---|
Example :
union ABC { char n[50]; int c.No; float s; }a1, a2, a[20]; |
---|
How to access members of a union
Two types of operators used for accessing members of a union.
- "."(Dot) - Member operator
- "-> " - Structure pointer operator (done using pointers)
Example :
#include<stdio.h> #include <string.h> union employee { int id; char name[50]; }e1; //declaring e1 variable for structure int main( ) { //store first employee information e1.id=1851878721; //copying string into char array strcpy(e1.name, "Aman singh"); //printing first employee information printf( "employee 1 id : %d\n", e1.id); printf( "employee 1 name : %s\n", e1.name); return 0; } |
---|
Output :
employee 1 id : 1851878721
employee 1 name : Aman singh
Example-2 :
#include<stdio.h> #include<conio.h> union test { int x; char y; }; int main() { union test p1; p1.x = 6; // p2 is a pointer to union p1 union test* p2 = &p1; // Accessing union members using pointer printf("%d %c", p2->x, p2->y); return 0; } |
---|
Output : 6
Difference between Structures and Unions
STRUCTURES | UNION |
---|
Struct keyword is used to declare the structure | Union keyword is used to declare the Union |
Structure variable will allocate memory for all the structure members separately. | Union variable will allocate common memory for all the union members. |
Example: struct Employee{ int age; char name[50]; float salary; }; | Example: union Employee{ int age; char name[50]; float salary; }; |
Structures will occupy more memory space. | Union will occupy less memory space |
It allows us to access any or all the members at any time. | It allows us to access only one union member at a time. |
For more RTU/BTU II Sem Computer Programming Lab Experiments CLICK HERE