C program to find the size of the union

Here, we are going to learn how to find the size of the union using C program? By Nidhi Last updated : March 10, 2024

Problem statement

Here, we will create a union with some members and then we print the size of the union on the console screen. The union allocates the space of one member at a time.

C Program to Find the Size of a Union

The source code to find the size of the union is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find the size of union

#include <stdio.h>

union MyUnion {
    int num1;
    float num2;
};

int main()
{
    union MyUnion UN;

    printf("Size of union: %ld", sizeof(UN));

    UN.num1 = 10;
    printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);

    UN.num2 = 10.34F;
    printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);

    return 0;
}

Output

Size of union: 4
Num1: 10, Num2: 0.000000
Num1: 1092972708, Num2: 10.340000

Explanation

Here, we created a union MyUnion that contains two members num1 and num2. The union allocates space for only one member at a time. Then we created the union variable UN in the main() function. After that, we get the size of the union using the sizeof() operator, and set the value of variables one by one, and print the value of variables on the console screen.

C Structure & Union Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.