i2tutorials

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:

 

 

Record2 union variable:

 

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

 

Exit mobile version