C Program to Find the Size of a Union


This is a C program to find the size of a Union.

Problem Description

This Program finds the size of a Union.

Problem Solution

1. Define the union.
2. Finds its size using keyword sizeof().
3. Print the same and exit.

Program/Source Code

Here is source code of the C program to find the size of a Union. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to find the size of a union
  3.  */
  4. #include <stdio.h>
  6. void main()
  7. {
  8.     union sample
  9.     {
  10.         int   m;
  11.         float n;
  12.         char  ch;
  13.     };
  14.     union sample u;
  16.     printf("The size of union = %d\n", sizeof(u));
  17.     /*  initialization */
  18.     u.m = 25;
  19.     printf("%d %f %c\n", u.m, u.n, u.ch);
  20.     u.n = 0.2;
  21.     printf("%d %f %c\n", u.m, u.n, u.ch);
  22.     u.ch = 'p';
  23.     printf("%d %f %c\n", u.m, u.n, u.ch);
  24. }
Program Explanation

1. Define the union named sample.
2. Declare three variables m, n and ch of different data types.
3. Use the keyword sizeof() to find the size of a union and print the same.
4. Initialize each variable with some value and print its value as output.
5. Exit.

Runtime Test Cases
The size of union = 4
25 0.000000 
1045220557 0.200000
1045220464 0.199999

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.

Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & 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, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn