52 C Program to Illustrate the Concept of Unions
Posted by Superadmin on December 24 2015 02:23:23
This C Program illustrates the concept of unions. A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. Unions provide a way to manipulate different kinds of data in a single area of storage, without embedding any machine-dependent information in the program.
Here is source code of the C program to illustrate the concept of unions. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to illustrate the concept of unions
*/
#include <stdio.h>
void main()
{
union number
{
int n1;
float n2;
};
union number x;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 = %d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%f", &x.n2);
printf("Value of n2 = %f\n", x.n2);
}
$ cc pgm93.c
$ a.out
Enter the value of n1: 10
Value of n1 = 10
Enter the value of n2: 50
Value of n2 = 50.000000