Home >Backend Development >C++ >Application of anonymous unions and structures in C language

Application of anonymous unions and structures in C language

WBOY
WBOYforward
2023-09-16 18:45:02758browse

Application of anonymous unions and structures in C language

Here we take a look at what are anonymous unions and structures in C language. Anonymous unions and structures are unnamed unions and structures. Since they have no name, we cannot create a direct object of it. We use it as a nested structure or union.

These are examples of anonymous unions and structures.

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

In this example we are creating a structure called point which holds an anonymous structure. It holds two values ​​x, y. We can directly access anonymous structures or union members.

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)

The above is the detailed content of Application of anonymous unions and structures in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete