开发者

What is the use of declaring anonymous structures within a structure?

What is the use of defining a anonymous structure within 开发者_如何学Pythona structure? When should this concept be used?


I sometimes use it to create a union between some data:

typedef union {
    struct {
        int x, y, z;
    };
    int elements[3];
} Point;

This way I can easily loop over the coordinates with elements but also use the shorter form x, y and z instead of elements[0] etc.


It's perfectly fine if you just want to express that two values belong together, but never need the particular grouping as a stand-alone type.

It might be seen as a bit pedandic and leaning towards the over-engineering side of things, but it can also be seen as a big way to add clarity and structure.

Consider:

struct State
{
  Point position;
  float health;
  int level;
  int lives_left;
  int last_checkpoint;
  char filename[32];
};

versus

struct State
{
  struct
  {
  Point position;
  float health;
  int level;
  int lives_left;
  }               player;
  struct {
  int last_checkpoint;
  char filename[32];
  }               level;
}

The last case is a bit harder to indent clearly, but it does express in a very clear way that some of the values are associated with the player, and some with the level.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜