In C programming, a union is a user-defined data type that allows storing different data types in the same memory location. The size of a union is determined by the size of its largest member. In this program, we will calculate the size of a union.
Problem statement
Write a C program to find the size of a union.
C Program to Find the Size of a Union
#include <stdio.h>
union Data {
int num;
float fraction;
char character;
};
int main() {
union Data data;
int size;
size = sizeof(data);
printf("Size of the union: %d bytes\n", size);
return 0;
}
how it works
- We start by including the necessary header file
stdio.hto use theprintffunction. - We define a union named
Datawith three members:numof typeint,fractionof typefloat, andcharacterof typechar. - In the
mainfunction, we declare a variabledataof typeunion Dataand an integer variablesize. - Using the
sizeofoperator, we calculate the size of thedataunion and assign it to thesizevariable. - Finally, we print the size of the union using the
printffunction.
Input/Output
