Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

structure

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

like image 292
Jay Avatar asked May 03 '10 09:05

Jay


2 Answers

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.

like image 143
Andreas Brinck Avatar answered Nov 14 '22 12:11

Andreas Brinck


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.

like image 20
unwind Avatar answered Nov 14 '22 12:11

unwind