C Program to Illustrate the Concept of Unions

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.

  1. /*
  2.  * C program to illustrate the concept of unions
  3.  */
  4. #include <stdio.h>
  6. void main()
  7. {
  8.     union number
  9.     {
  10.         int  n1;
  11.         float n2;
  12.     };
  13.     union number x;
  15.     printf("Enter the value of n1: ");
  16.     scanf("%d", &x.n1);
  17.     printf("Value of n1 = %d", x.n1);
  18.     printf("\nEnter the value of n2: ");
  19.     scanf("%f", &x.n2);
  20.     printf("Value of n2 = %f\n", x.n2);
  21. }

$ 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

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics of C, go to C Programming Examples.
Subscribe Newsletter & Posts

Manish Bhojasia, a technology veteran with 17+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer and SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage & Cluster Administration, Advanced C Programming, SAN Storage Technologies, SCSI Internals and Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him below.

Practice Interview Questions & Answers, Quizzes, Objective, Multiple Choice Aptitude Tests for Freshers and Experienced People in these topics - Learn C, C++, Java and C# Programming with coding example on Simple problems as well as tough Algorithms and Data-structures along with runtime output: - C Programs, Data-Structures and Algorithms, C++ Algorithms, Java Algorithms, C# Programs, Android Programs in Java

C Tutorials and Linux Commands Tutorial - C Tutorials, Linux Commands

Career Mentoring with our Founder / CTO - Read More