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