Unions in C (original) (raw)

Last Updated : 25 Oct, 2025

A union is a user-defined data type that can hold different data types, similar to a structure.

#include <stdio.h>

// Define a union with // different data types union Student { int rollNo; float height; char firstLetter; };

int main() {

// Declare a union variable
union Student data;

// Assign and print the roll number
data.rollNo = 21;
printf("%d\n", data.rollNo);
data.height = 5.2;
printf("%.2f\n", data.height);
data.firstLetter = 'N';
printf("%c", data.firstLetter);

return 0;

}

`

Union Declaration

A union is declared similarly to a structure. Provide the name of the union and define its member variables.

Size of Union

The size of the union will always be equal to the size of the largest member of the union. All the less-sized elements can store the data in the same space without any overflow.

C `

#include <stdio.h>

union A{ int x; char y; };

union B{ int arr[10]; char y; };

int main() {

// Finding size using sizeof() operator
printf("Sizeof A: %ld\n", sizeof(union A));
printf("Sizeof B: %ld\n", sizeof(union B));
return 0;

}

`

Output

Sizeof A: 4 Sizeof B: 40

The above unions' memory can be visualized as shown:

Nested Union

In C, we can define a union inside another union like **structure. This is called **nested union and is commonly used when you want to efficiently organize and access related data while sharing memory among its members.

C `

#include <stdio.h>

// Define a union with // different data types union Student { int rollNo; union Academic{ int marks; } performance; };

int main() {

// Declare a union variable
union Student abc;

// Assign and print the 
// roll number
abc.rollNo = 21;
printf("%d\n", abc.rollNo);

// Assign and print the 
// member of inner union
abc.performance.marks = 91;
printf("%d", abc.performance.marks);
return 0;

}

`

Anonymous Union

An anonymous union in C is a union that does not have a name. Instead of accessing its members through a named union variable, you can directly access the members of the anonymous union. This is useful when you want to access the union members directly within a specific scope, without needing to declare a union variable.

C `

#include <stdio.h>

// Define a union with // different data types struct Student { int rollNo;

// Anonymous union
union {
    int marks;
} performance;

};

int main() {

// Declare a structure variable
struct Student abc;

abc.rollNo = 21;
printf("%d\n", abc.rollNo);

// Assign and print the member of anonymous union
abc.performance.marks = 91;
printf("%d", abc.performance.marks);

return 0;

}

`

Applications of Union in C

Next Read