문제

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