C Program to Find the Size of a Union

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

  1. We start by including the necessary header file stdio.h to use the printf function.
  2. We define a union named Data with three members: num of type int, fraction of type float, and character of type char.
  3. In the main function, we declare a variable data of type union Data and an integer variable size.
  4. Using the sizeof operator, we calculate the size of the data union and assign it to the size variable.
  5. Finally, we print the size of the union using the printf function.

Input/Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...