tags:

views:

106

answers:

2

What is the use of defining a anonymous structure within a structure? When should this concept be used?

+5  A: 

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.

Andreas Brinck
+2  A: 

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.

unwind