C Program to illustrate the concept of Unions

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

In this c program, we have to illustrate the concept of unions. For that, we have to know something about unions.

What is the union?

We all know that union is a particular data type available in c, storing different data types in the same memory location. We can define a union with many members, but only one member can contain a value at a given time. In a program, a union is defined in the same way as we define a structure in a c program. For accessing any member of a union, a member access operator is used. Union represents a new data type with more than one member of the program.

What is the difference between union and structure?

The main difference between structure and union is that only we can access only one member at a time for union, but in the case of structure, we can access all of its members at any time. The size of the union almost corresponds to the size of the largest member.

What is the syntax of a union declaration?

The Syntax of the Union declaration is given by

union union_name
{
type element 1;

type element 2;
……………..

type element n;
};

In this C program, we have to declare the Union number, which has the members n1 and n2. Then we declare a variable x of type number. Then we read the value of n1, and we display the value of n1 using the printf function. Then we read the value of n2, and we show it by using the printf function.

ALGORITHM

STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare the Union, number with members n1 and n2.

STEP 3: Declare x as the variable of number.

STEP 4: Read the value of n1 into the variable x.n1.

STEP 5: Display value of n1 as x.n1 using printf function.

STEP 6: Read the value of n2 into the variable x.n2.

STEP 7: Display the value of n2 using printf function.

C Source Code

                                          #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("%d", & x.n2);
  printf("Value of n2 = %d\n", x.n2);
} /* End of main() */
                                      

OUTPUT

Enter the value of n1: 2
Value of n1 =2

Enter the value of n2: 3
Value of n2 = 0