C Program to find the size of a Union

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

In this C program, we have to find the size of unions. For that, we have to know something about Unions.

What is the union?

We all know that the union is a particular data type available in c, storing different data types in the same memory location. We can define a union with many members, but only one member can contain a value at a given time. In a program, a union is defined in the same way as we define a structure in a c program. For accessing any member of a union, a member access operator is used. Union defines a new data type with more than one member for the program.

What is the difference between union and structure?

The main difference between structure and union is that we can access only one member at a time for 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.

What is the syntax of a union declaration?

The Syntax of the Union declaration is given by

union union_name
type element 1;

type element 2;

type element n;

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 the Union 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.


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

STEP 2: Declare the Union, a 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.

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() */



The size of uni sizeof(u)

25 0.000000 

1045220557 0.200000 ?

1045220464 0.199999 p