/    /  Program for C union

Program for C union

 

#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju"); // Garbage Value will be printed
strcpy(record1.subject, "Maths"); // Garbage Value will be printed
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;}

 

Output:

 

Program for C union

 

Explanation For Above C Union Program:

 

There are 2 union variables reported in this program to understand difference in access to union members’ values.

 

Record1 union variable:

 

  • “Raju” is assigned to the union member “record1.name”. The memory location name is ‘record1.name’ and the value recorded at that location is ‘Raju’.
  • Next, “Maths” is assigned to the union member “record1.subject.” Now the name of the memory location is changed to “record1.subject” with the value “Maths” (Union can only hold one member at a time).
  • Then “86.50” goes to the union member “record1.percentage”. Now the memory location name is changed to ‘record1.percentage’ with the value ‘86.50′.
  • Thus, the name and value of union membership are replaced every time on the common storage space.
  • So we still have access to only one union member for whom the value is finally allocated. We do not have access to other member values.
  • Therefore, only “record1.percentage” is shown in the result. “record1.name” and ‘record1.percentage’ are empty.

 

Record2 union variable:

 

  • If we want to have access to all member values with the help of the union, we must have access to the member before assigning values to other members as shown in record2 union variable in this program.
  • Each union member is available in the record2 example immediately after attaching values.
  • If we do not access it before assigning values to other members, the name and value of the member will be overridden by other members because all members use the same memory.

We can’t access all members of the union at the same time, but the structure can do that.