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 finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...