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 Books in C Programming, Data-Structures and Algorithms

Note: Join free Sanfoundry classes at Telegram or Youtube
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.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.