我尝试了以下代码
#include <stdio.h>
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;这样的代码不是很有意义吗?
或者我错在哪里了?!
发布于 2011-12-30 06:33:20
是的,正如您在标准中发现的那样,typedef是一个存储类说明符。在某种程度上,这是语法上的便利,但您可以使用typedef或更“明显”的存储类说明符,这是有意为之的。
type声明为类型创建一个别名。
在声明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;发布于 2011-12-30 06:32:58
也许标准应该将这些东西称为storage-class-or-typedef-specifier,并说:
约束:在一个声明中的声明说明符中最多只能给出一个存储类或类型定义说明符
然后他们就不需要添加关于语义的注释了。
关于语义的评论只是简单地说,typedef实际上并不控制用于该类型的存储的任何东西(因此它在语义上不是“存储说明符”),但它在语法上像其他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();
}请注意,您使用预处理器来获得“静态类型定义”效果,这将使bar()成为一个静态函数。这可能不是你想要的效果。也许吧。
发布于 2011-12-30 06:33:42
你不能这样做--至少不能用MinGW的GCC --无论是在函数内部还是外部。
我会使用预处理器:
#include <stdio.h>
#define sint static int
int main(void)
{
sint i = 10;
return 0;
}达到了同样的效果。
我想这是因为"static int“不是像"volatile int”那样的类型。
https://stackoverflow.com/questions/8674236
复制相似问题