Join Regular Classroom : Visit ClassroomTech

How to calculate the size of an union in C?

In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data. Members can be stored in a union at any time. The size of a union is sufficient to contain the largest of its data members. Each data member is allocated as if it were the sole member of a struct

Don’t know what is union? Read: Unions in C

Let us observe the source code of the C program to find the size of a Union.

/* C program to calculate the size of a union */
/* www.codewindow.in */

#include <stdio.h>

union codewindow {    // Define the union named codewindow.
     int s;
     float k;
     char c;
};  // Declare three variables s, k and c of different data types.
 
int main() {
	union codewindow u;
	int size = sizeof(u);    // Use the keyword sizeof() to find the size of a union and print the same.

	printf("The size of union = %d\n", size);

	return 0;
}

Output:

The size of union = 4

Explanation:

Datatype int has the highest size between all the members i.e float and char and we know that, Size of any union = Size of the largest member in the union. So the size of the union will be 4 bytes as the size of datatype int has 4 bytes which is the highest.


You Missed

Also Checkout