为什么“struct"关键字必须在 C 中的 struct 实例之前? [英] Why must the 'struct' keyword precede struct instances in C?
问题描述
假设我在 C 中定义了一个结构体.如果我声明了该结构体的一个实例,则必须在其前面包含 'struct' 关键字.
Let's say I define a struct in C. If I declare an instance of that struct, it's necessary that I include the 'struct' keyword in front of it.
// Define struct
struct Book {
char title[50];
char author[50];
char subject[100];
int book_id;
};
// Instantiate struct
int main()
{
struct Book myBook;
}
我的问题:为什么 struct 关键字必须先于结构的任何实例化?似乎编译器会有大量信息来推断Book"是一个结构体.
My question: why is it necessary for the struct keyword to precede any instantiation of the struct? It seems like the compiler would have plenty of information to deduct that 'Book' is a struct.
我知道你可以通过使用 typedef 来解决这个问题,但这真的只是编译器应该已经知道的东西的样板代码.
I realize you can get around this by using a typedef, but that really just seems like boiler plate code for something the compiler should already know.
推荐答案
由于使用关键字 struct、union 和 enum 名称,这些类型可以形成自己的命名空间,不会与其他实体的名称冲突.
Due to using the keywords struct, union and enum names for these types can form their own namespace that will not conflict with names of other entities.
例如
#include <stdio.h>
int main(void)
{
struct Book
{
const char *Book;
} Book = { "The first favorite book" };
struct Book otherBook = { .Book = "The second favorite book" };
puts( Book.Book );
puts( otherBook.Book );
return 0;
}
这篇关于为什么“struct"关键字必须在 C 中的 struct 实例之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!