Question

So I was looking through this C tutorial and I found these lines of code:

struct Monster {
    Object proto;
    int hit_points;
};
typedef struct Monster Monster;

And I thought that it would make much more sense if it were like this:

typedef struct {
    Object proto;
    int hit_points;
} Monster;

I could could be totally wrong, because I am very new to C, but I would assume both these pieces of code would do the same thing. So is they do, then is there any reason to prefer one over the other? Or if they are different, what makes them different? Thanks!

Était-ce utile?

La solution 2

There are times when the second form won't work. Say you want to create a linked list of Monsters. With the first form, you can add a pointer to the next Monster in the struct.

struct Monster {
    Object proto;
    int hit_points;
    struct Monster* next;
};

You can't do that in the second form since the struct doesn't have a name.

Autres conseils

The first piece of code defines a type struct Monster, and then gives it another name Monster.

The second piece of code defines structure with no tag, and typedef it as Monster.

With either code, you can use Monster as the type. But only in the first code, you can also use struct Monster.

The definitions (from the first part of the question - plus my liberal re-formating):

struct Monster
   {
   Object proto;
   int hit_points;
   };

typedef struct Monster Monster;

Is equivalent to:

typedef struct Monster
   {
   Object proto;
   int hit_points;
   } Monster;

My preference is:

typedef struct MONSTER_S
   {
   Object proto;
   int hit_points;
   } MONSTER_T;

FYI... a struct name isn't required. So if the code only needs to use the type, the following is also fine:

typedef struct
   {
   Object proto;
   int hit_points;
   } MONSTER_T;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top