質問

I have recently started out in C and want to know the difference between

typedef struct 
{
      char *name;
      int age;
} Person;

and

struct Person
{
       char *name;
       int age;
}
typedef struct Person Person;

thank you

役に立ちましたか?

解決

There is no difference as such. typedef just creates alias of a present datatype.

However, in first case you can declare the struct variables as Person me;, i.e. using Person only. In second case you can either use Person me; or struct Person me; both are valid.

I find latter one more readable and understandable.

Extra Notes:
BTW your second declaration has a minor syntactic error:

struct Person
{
       char *name;
       int age;
}; // You missed this ';'
typedef struct Person Person;

You can also combine these two statements as:

typedef struct Person
{
       char *name;
       int age;
}
Person;

他のヒント

In the second example, the struct is also given the name (called "the struct tag") Person, but in the first version that is omitted, making Person the only name for the structure.

I prefer the former whenever possible, there's no need to introduce extra names.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top