简体   繁体   English

`typedef struct X {}`和`typedef struct {} X`有什么区别?

[英]What's the difference between `typedef struct X { }` and `typedef struct { } X`?

What's the difference between these two declarations in C: C中这两个声明之间有什么区别:

typedef struct square{

   //Some fields

};

and

typedef struct{  

           //Some fields

} square;

The first declaration: 第一个宣言:

typedef struct square {
    // Some fields
};

defines a type named struct square . 定义一个名为struct square的类型。 The typedef keyword is redundant (thanks to HolyBlackCat for pointing that out). typedef关键字是多余的(感谢HolyBlackCat指出这一点)。 It's equivalent to: 它相当于:

struct square {
   //Some fields
};

(The fact that you can use the typedef keyword in a declaration without defining a type name is a glitch in C's syntax.) (事实上​​,您可以在声明中使用typedef关键字而不定义类型名称,这是C语法中的一个小故障。)

This first declaration probably should have been: 第一个声明应该是:

typedef struct square {
    // Some fields
} square;

The second declaration: 第二个宣言:

typedef struct {
    // Some fields
} square;

defines an anonymous struct type and then gives it the alias square . 定义一个匿名struct类型,然后给它别名square

Remember that typedef by itself doesn't define a new type, only a new name for an existing type. 请记住, typedef本身并不定义新类型,只定义现有类型的新名称。 In this case the typedef and the (anonymous) struct definition happen to be combined into a single declaration. 在这种情况下, typedef和(匿名) struct定义碰巧组合成一个声明。

struct X { /* ... */ };

That create a new Type. 这创造了一个新的类型。 So you can declare this new type by 所以你可以通过声明这个新类型

struct X myvar = {...}

or 要么

struct X *myvar = malloc(sizeof *myvar);

typdef is intended to name a type typdef旨在命名一种类型

typedef enum { false, true } boolean;
boolean b = true; /* Yeah, C ANSI doesn't provide false/true keyword */

So here, you renamed the enum to boolean. 所以在这里,你将enum重命名为boolean。

So when you write 所以当你写作

typedef struct X {
    //some field
} X;

You rename the type struct X to X. When i said rename, it's more an other name. 您将类型struct X重命名为X.当我说重命名时,它更像是另一个名称。

Tips, you can simply write : 提示,你可以简单地写:

typedef struct {
    //some field
} X;

But if you need a field with the same type (like in a linked list) you had to give a name to your struct 但是如果你需要一个具有相同类型的字段(比如在链表中),你必须给你的结构命名

typedef struct X {
    X *next; /* will not work */
    struct X *next; /* ok */
} X;

Hope this helps :) 希望这可以帮助 :)

Edit : As Keith Thompson said, typdef is intended to create alias :) 编辑:正如Keith Thompson所说,typdef旨在创建别名:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM