我尝试了以下代码
#include <stdio.h>
int main(void)
{
typedef static int sint;
sint i = 10;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
并遇到以下错误:
error: multiple storage classes in declaration specifiers
Run Code Online (Sandbox Code Playgroud)
当我提到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;
Run Code Online (Sandbox Code Playgroud)
我能找到的唯一解释(基于一些互联网搜索和交叉引用C99规范中的各个部分)是syntactic convenience only to make the grammar simpler
.
我正在寻找关于类型名称如何具有存储类说明符的一些理由/解释?
拥有像这样的代码是否有意义typedef static int sint;
?
或者我哪里错了?!
CB *_*ley 17
是的,typedef
是标准中的存储类说明符.在某种程度上,这是一种语法上的便利,但有意识的是,你可以拥有一个typedef
或更"明显"的存储类说明符.
typedef声明为类型创建别名.
在声明中static int x;
的类型x
是int
.static
与类型无关.
(考虑到如果你取地址x
,&x
有类型int*
.int *y = &x;
会是合法的,static int *z = &x
但后者static
影响存储类,z
并且独立于存储类x
.)
如果允许这样的东西,static
则没有效果,因为没有声明对象.别名的类型就是int
.
typedef static int sint;
Run Code Online (Sandbox Code Playgroud)
也许标准应该称这些东西storage-class-or-typedef-specifier
并说:
约束:最多可以在声明中的声明说明符中给出一个storage-classor-typedef-specifier
然后他们就不必添加关于语义的注释.
关于语义的评论只是说typedef
实际上并没有控制任何关于该类型的存储(因此它在语义上不是'存储说明符'),而是它在语法上像其他一样处理storage-class-specifier
,因此不能与他们一起使用.
因此,a 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();
}
Run Code Online (Sandbox Code Playgroud)
请注意,您使用预处理器来获取'static typedef'效果,这将产生bar()
静态函数.这可能不是你想要的效果.也许.