fgs*_*gts 1 c standards struct typedef
在C中,可以定义struct,typedefed,并声明为:
typedef struct {
int bar;
} Foo;
Foo foo;
Run Code Online (Sandbox Code Playgroud)
要么:
struct Foo {
int bar;
} foo;
typedef struct Foo Foo;
Run Code Online (Sandbox Code Playgroud)
我认为这有点不一致,而且过于冗长.我希望它能像C++一样工作.
在C++中,您不需要指定typedef struct Foo Foo;能够声明结构Foo foo;而不是struct Foo foo;.为什么没有将它引入C标准或作为编译器标志选项?是否有任何C代码的例子如果typedef struct在C中被选为可选的话会破坏?
这是可选的.
struct mystruct {
int x;
};
struct mystruct y;
Run Code Online (Sandbox Code Playgroud)
结构定义位于"标记"名称的单独名称空间中.这样它们就不会与函数或变量名冲突,所以你可以这样做:
struct stat st;
int r = stat("/path/file.txt", &st);
Run Code Online (Sandbox Code Playgroud)
您注意到stat函数的名称和结构的名称,但它们不会发生冲突?这是一个真实的例子,见stat(2).如果你消除了这个,旧的代码将无法编译.该typedef会在相同的命名空间函数和变量的名称.
struct stat { ... };
int stat(const char *path, struct stat *buf);
typedef struct stat stat; // ERROR
Run Code Online (Sandbox Code Playgroud)
一些样式指南主张不使用typedef,只需键入struct stat任何地方.无论您是否同意这一点,它都是在各个地方(例如Linux内核!)的现有做法,C标准委员会反对破坏现有的C代码库.
在C++中,通过使struct可选项来维护与C代码的兼容性,但是如果定义一个与结构同名的函数,则需要struct在变量定义中显式使用:
stat st; // error! stat is a function
struct stat st; // Ok
int r = stat("/path/file.txt", &st);
Run Code Online (Sandbox Code Playgroud)