C Program to find the size of a Union


January 8, 2023, Learn eTutorial
1526

What is the Union?

Union is a particular data type available in C, that can able to store different data types in the same memory location. We can access the members of it using the member access operator. We can define it with many members, but only one member can contain a value at a given time. a union is defined in the same way as we define a structure.

The Syntax 

union name
{
type element 1;

type element 2;
……………..

type element n;
};

What is the difference between union and structure?

The main difference is that we can access only one member at a time for a union. But in the case of structure, we can access all of its members at any time.

The size of the union almost corresponds to the size of the largest member.

How to find the size of a union using the C program?

In this C program, we have to declare the union sample with the members m, n, ch. Then we declare a variable u of type sample. Then display the size of it by calling the function sizeof(). Assign u.m=25 and display u. m, u. n, u. ch ,Then assign u.n=0.2 and display u.m, u.n, u.ch ,assign c='p' and display u.m, u.n, u.ch.

ALGORITHM

STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare the Union, sample with members m,n, ch.

STEP 3: Declare u as the variable of the sample.

STEP 4: Display the size of Union u by using the function sizeof().

STEP 5: Assign u.m=25 and display u.m,u.n,u.ch using printf.

STEP 6: Assign u.n=0.2 and display u.m,u.n,u.ch using printf.

STEP 7: Assign u.c='p' and display u.m,u.n,u.ch using printf.


To find the size, we have to know the below C concepts, we recommend to refer those for a better understanding

C Source Code

                                          #include <stdio.h>

void main() {
    union sample {
      int m;
      float n;
      char ch;
    };
    union sample u;
    printf("The size of uni sizeof(u)\n");
    u.m = 25; /*initialization */ 
    printf("%d %f %c\n", u.m, u.n, u.ch); 
    u.n = 0.2; 
    printf("%d %f %c\n", u.m, u.n, u.ch); 
    u.ch = 'p'; 
    printf("%d %f %c\n", u.m, u.n, u.ch);
    } /*End of main() */

                                      

OUTPUT

The size of uni sizeof(u)

25 0.000000 

1045220557 0.200000 ?

1045220464 0.199999 p