ADVERTISEMENT
ADVERTISEMENT

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?
Submitted by Nidhi, on September 15, 2021

Problem Solution:

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.

Program:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.