Anonymous Unions

From Appmethod Topics
Jump to: navigation, search

Go Up to Unions Index

A union that does not have a tag and is not used to declare a named object (or other type) is called an anonymous union. It has the following form:

union { member_list };

Its members can be accessed directly in the scope where this union is declared, without using the x.y or p->y syntax.

Anonymous unions can be global, nested, or unnested. ANSI-C never allows anonymous unions. ANSI-C++ allows all three types of anonymous unions.

C++ Anonymous unions

An anonymous union cannot have member functions or private or protected members. At file level an anonymous union must be declared static. Local anonymous unions must be either automatic or static; in other words, an anonymous union cannot have external linkage. Unnested anonymous unions are only allowed in C++.

Nested anonymous unions

The outer structure, class, or union of a nested anonymous union must have a tag. C and C++ allow nested anonymous unions by default. In C only, a nested anonymous union can, optionally, have a tag.

Example:

struct outer {
  int x;
};

int main(void)
{
  struct outer o;
}