Union c programming
A union is a composite data type in C programming that allows you to store different types of data in the same memory location. A union uses a single memory location for all of its members as
opposed to structures, which assign each member a unique space in memory. As a result, only one of a union's members' values can be upheld at once, and the largest member determines the union's size.
syntax:-
union UnionName {
data_type member1;
data_type member2;
.........
};
example:-
#include <stdio.h>
#include<conio.h>
union AUnion {
int a;
float b;
char c;
};
int main() {
union AUnion u;
u.a = 42;
printf("Value of integer member: %d\n", u.a);
u.b= 3.14;
printf("Value of float member: %f\n", u.b);
u.c = 'U';
printf("Value of char member: %c\n", u.c);
getch();
}
explain:-
we define the union 'AUnion' with three members: an integer 'a', a float 'b', and a character 'c'. These members can have values assigned to them and be accessed, but because they all reside in the same memory location, only one member should be used at a time to prevent data corruption.