Skip to content

Unions

Union is a special class type that can hold only one of its non-static data members at any given time.

Unions were officially added to the NOI syllabus at the introductory level in 2023.

Defining a Union

The class specifier for a union declaration is similar to that of a class or structure:

1
2
3
4
union MyUnion {
  int x;
  long long y;
} x;

The definition of a union is similar to that of a structure. According to the above definition, MyUnion can also be used as a custom type. The name MyUnion can be omitted.

Accessing/Modifying Member Elements

Similar to structures, members can be accessed using variable_name.member_name.

The memory space occupied by a union is at least the size of its largest member, and all members share the same memory space and address. When a member is assigned a value, due to memory sharing, all other members in the union are overwritten. This means that a union can only hold the value of one member at any given time.

For more usage of unions, refer to cppreference: Union declaration.