VOOZH about

URL: https://www.geeksforgeeks.org/c/c-unions/

⇱ Unions in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Unions in C

Last Updated : 25 Oct, 2025

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

  • Unlike structures, all members of a union are stored in the same memory location. Since all members share the same memory, changing the value of one member overwrites the value of the others.
  • Union members can be accessed using the dot (.) operator. Example: u.member.
  • Unions are useful when you want to save memory by storing different types of data in the same memory space.

Output
21
5.20
N

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.


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.


Output
21
91

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.


Output
21
91

Applications of Union in C

  • Memory-efficient: Multiple data types share the same memory, reducing overall memory usage.
  • Hardware mapping: Useful for registers with different interpretations (e.g., status vs. command).
  • Single-type data: Ideal for data that can be one of several types but not simultaneously (e.g., message ID or string).

Next Read

Comment
Article Tags: