Anonymous Union and Structure in C

CServer Side ProgrammingProgramming

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)
raja
Published on 26-Apr-2019 12:34:16
Advertisements