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;
}
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.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer