Anonymous Union and Structure in C


Here we will see what is the anonymous union and structures in C. The anonymous unions and structures are unnamed unions and structures. As they have no names, so we cannot create direct objects of it. We use it as nested structures or unions.

These are the examples of anonymous union and structures.

struct {
   datatype variable;
   ...
};
union {
   datatype variable;
   ...
};

In this example we are making one structure, called point, it is holding an anonymous structure. This is holding two values x, y. We can access the anonymous structure or union members directly.

Example

#include<stdio.h>
struct point {
   // Anonymous structure
   struct {
      int x;
      int y;
   };
};
main() {
   struct point pt;
   pt.x = 10;
   pt.y = 20;
   printf("Point (%d,%d)", pt.x, pt.y); //anonymus members can be accessed directly
}

Output

Point (10,20)

Updated on: 30-Jul-2019

890 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements