我有一个在现有 typedef 结构中定义 typedef 结构的程序,我想知道为什么会出现编译错误。
程序如下:
typedef struct Outer
{
typedef struct Inner
{
int b;
}INNER;
INNER inner;
int a;
}OUTER;
int main()
{
OUTER obj;
obj.a = 10;
obj.inner.b=8;
return 0;
}
编译时出现以下错误::
test.c:3:5: error:expected specifier-qualifier-list before ‘typedef’
test.c: In function ‘main’:
test.c:17:5: error: ‘OUTER’ has no member named ‘a’
test.c:18:5: error: ‘OUTER’ has no member named ‘inner’
但是,当我把程序改成
typedef struct Outer
{
struct Inner
{
int b;
};
struct Inner inner;
int a;
}OUTER;
int main()
{
OUTER obj;
obj.a = 10;
obj.inner.b=8;
return 0;
}
编译成功
为什么内部结构不允许使用 typedef?
最佳答案
C 不允许在结构成员的声明中使用存储类说明符(typedef
,但也不允许使用 static
或 extern
)。这在C99 6.7.2.1p1 的结构和 union 声明语法中有规定。
/* The compiler will issue a diagnostic for this declaration */
struct s {
static int a;
};
您可以将 6.7.2.1p1 语法与 6.7p1 中声明符不是函数参数或结构/union 成员的声明语法进行比较,并发现在这种情况下允许使用存储类说明符。
关于c - 为什么内部结构中不允许使用 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10984418/