Anonymous Union and Structure in C
In C11 standard of C, anonymous Unions and structures were added.
Anonymous unions/structures are also known as unnamed unions/structures as they don’t have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions.
Definition is just like that of a normal union just without a name or tag. For example,
// Anonymous union example
union
{
char alpha;
int num;
};
// Anonymous structure example
struct
{
char alpha;
int num;
};
Since there is no variable and no name, we can directly access members. This accessibility works only inside the scope where the anonymous union is defined.
Following is a complete working example of anonymous union.
// C Program to demonstrate working of anonymous union #include<stdio.h> struct Scope { // Anonymous union union { char alpha; int num; }; }; int main() { struct Scope x; x.num = 65; // Note that members of union are accessed directly printf("x.alpha = %c, x.num = %d", x.alpha, x.num); return 0; } |
Output:
x.alpha = A, x.num = 65
// C Program to demonstrate working of anonymous struct #include<stdio.h> struct Scope { // Anonymous structure struct { char alpha; int num; }; }; int main() { struct Scope x; x.num = 65; x.alpha = 'B'; // Note that members of structure are accessed directly printf("x.alpha = %c, x.num = %d", x.alpha, x.num); return 0; } |
Output:
x.alpha = B, x.num = 65
What about C++?
Anonymous Unions and Structures are NOT part of C++ 11 standard, but most of the C++ compilers support them. Since this is a C only feature, the C++ implementations don’t allow to anonymous struct/union to have private or protected members, static members, and functions.
This article is contributed by Nikita Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Difference between Structure and Union in C
- C | Structure & Union | Question 4
- C | Structure & Union | Question 10
- C | Structure & Union | Question 9
- C | Structure & Union | Question 10
- C | Structure & Union | Question 2
- C | Structure & Union | Question 1
- C | Structure & Union | Question 5
- C | Structure & Union | Question 6
- C | Structure & Union | Question 7
- C | Structure & Union | Question 8
- Output of C programs | Set 44 (Structure & Union)
- Output of C++ programs | Set 41 (Structure and Union)
- Union in C
- Difference between Structure and Array in C



