【发布时间】:2012-07-08 13:15:07
【问题描述】:
我在头文件中有以下声明:
struct my_struct;
int func(struct my_struct* s); // Passing struct my_struct*
如果没有前向声明,编译器显然会给出this error:
error: 'struct my_struct' declared inside parameter list
但是,如果我用 typedef 替换 my_struct 的前向声明,并相应地更新函数声明,它 compiles fine:
typedef struct my_struct my_struct_t;
int func(mystruct_t* s); // Passing my_struct_t*
奇怪的是,如果我保留 typedef,但使用原始声明 my_struct,它是 also compiles:
typedef struct my_struct my_struct_t;
int func(struct my_struct* s); // Passing struct my_struct*
其他人注意到了吗?这种行为是副作用吗?
【问题讨论】:
-
typedef 也充当前向声明,它将类型名称带入范围。
-
@DanielFischer 是的,我注意到了 :) 但我在标准中找不到任何说明。我错过了什么吗?
-
不需要前向声明来创建指向结构的指针。这只是一个约定。我错了吗?
-
加桑你错了。不声明名称就不能使用指向结构的指针。
-
@Ghasan 可以,但不能在函数参数列表中。见link。
标签: c typedef forward-declaration