typedef是存储类说明符吗?

我尝试了以下代码

#include  int main(void) { typedef static int sint; sint i = 10; return 0; } 

并发出以下错误:

 error: multiple storage classes in declaration specifiers 

当我提到C99规范时,我发现typedef是一个storage class

 6.7.1 Storage-class specifiers Syntax storage-class-specifier: typedef extern static auto register Constraints: At most, one storage-class specifier may be given in the declaration specifiers in a declaration Semantics: The typedef specifier is called a ''storage-class specifier'' for syntactic convenience only; 

我能找到的唯一解释(基于一些互联网搜索和交叉引用C99规范中的各个部分) syntactic convenience only to make the grammar simpler

我正在寻找关于类型名称如何具有存储类说明符的一些理由/解释?

拥有像typedef static int sint;这样的代码是不合理的typedef static int sint;

或者我哪里错了?!

是的, typedef是您在标准中找到的存储类说明符。 在某种程度上,这是一种语法上的便利,但故意要么你可以拥有typedef 或者一个更“明显”的存储类说明符。

typedef声明为类型创建别名。

在声明static int x; x的类型是intstatic与类型无关。

(考虑到如果你取x的地址, &x类型为int* int *y = &x;将是合法的,因为static int *z = &x但后者static影响z的存储类并且独立于存储x类。)

如果允许这样的东西, static就没有效果,因为没有声明对象。 别名的类型只是int

 typedef static int sint; 

也许标准应该称这些东西为storage-class-or-typedef-specifier并说:

约束:最多可以在声明中的声明说明符中给出一个storage-classor-typedef-specifier

然后他们就不必添加关于语义的注释。

关于语义的评论只是说typedef实际上并不控制关于用于该类型的存储的任何内容(因此它在语义上不是’存储说明符’),而是在语法上像其他storage-class-specifier一样处理storage-class-specifier ,因此不能与它们一起使用。

因此, typedef无法确定将存储特定类型实例的位置 – 这是由实例的实际声明(隐式或显式)确定的。

即使你正在寻找的东西是允许的,这也是不好的做法,我敢肯定。 考虑:

 // in someheader.h typedef static int sint; // now in foo.c #include "someheader.h" int foo(void) { sint i = 10; // unless you're intimately knowledgeable about how // `sint` is typedef'ed, this looks exactly like // an automatic // do some stuff that modifies `i`... return i; } sint bar(void) // what does this mean? is `bar()` static? { return foo(); } 

请注意,您使用预处理器来获取’static typedef’效果,这会使bar()成为静态函数。 这可能不是你想要的效果。 也许。

你不能这样做 – 至少不能用MinGW的GCC – 在函数内部或外部。

我会改用预处理器:

 #include  #define sint static int int main(void) { sint i = 10; return 0; } 

获得相同的结果。

我想是因为“static int”不是“volatile int”的类型。

typedef在语法上与存储类相同。 它不是存储类。 typedef与#define类似,但是typedef由Compiler解释,而#define由预处理器解释。 typedef可以进行超出预处理器function的文本替换。

使用typedef的两个目的1.可移植性2.更好的文档