UNIT-V Union
UNIT-V Union
void main(){
union Student stud_2; // using union keyword
printf("Enter details of stud_1 : \n");
printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);
In the above example program, the union variable "stud_1 is created while defining the union and the variable
"stud_2 is careted using union keyword. Whenever we access the members of a union we use the dot (.) operator.
Memory allocation of Union
When the unions are used in the c programming language, the memory does not allocate on defining union. The
memory is allocated when we create the variable of a particular union. As long as the variable of a union is created
no memory is allocated. The size of memory allocated is equal to the maximum memory required by an individual
member among all members of that union. In the above example program, the variables stud_1 and stud_2 are
allocated with 30 bytes of memory each.