gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:53:17 24 4
gpt4 key购买 nike

C 中这两个声明有什么区别:

typedef struct square{

//Some fields

};

typedef struct{  

//Some fields

} square;

最佳答案

第一个声明:

typedef struct square {
// Some fields
};

定义了一个名为struct square 的类型。 typedef 关键字是多余的(感谢 HolyBlackCat 指出这一点)。它相当于:

struct square {
//Some fields
};

(事实上,您可以在声明中使用 typedef 关键字而不定义类型名称,这是 C 语法中的一个错误。)

第一个声明可能应该是:

typedef struct square {
// Some fields
} square;

第二个声明:

typedef struct {
// Some fields
} square;

定义一个匿名的 struct 类型,然后给它起别名 square

请记住 typedef 本身并没有定义新类型,只是为现有类型定义了一个新名称。在这种情况下,typedef 和(匿名的)struct 定义恰好合并到一个声明中。

关于c - `typedef struct X { }` 和 `typedef struct { } X` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26724596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com