bit*_*ask 34 c typedef function-declaration
比方说,我有一系列具有相同原型的功能
int func1(int a, int b) {
// ...
}
int func2(int a, int b) {
// ...
}
// ...
Run Code Online (Sandbox Code Playgroud)
现在,我想简化他们的定义和声明.当然我可以使用这样的宏:
#define SP_FUNC(name) int name(int a, int b)
Run Code Online (Sandbox Code Playgroud)
但是我想把它保存在C中,所以我尝试使用存储说明符typedef:
typedef int SpFunc(int a, int b);
Run Code Online (Sandbox Code Playgroud)
这似乎适用于声明:
SpFunc func1; // compiles
Run Code Online (Sandbox Code Playgroud)
但不是定义:
SpFunc func1 {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
Run Code Online (Sandbox Code Playgroud)
有没有办法正确地做到这一点还是不可能?根据我对C的理解,这应该有效,但事实并非如此.为什么?
注意,gcc理解我要做的事情,因为,如果我写的话
SpFunc func1 = { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
它告诉我
error: function 'func1' is initialized like a variable
Run Code Online (Sandbox Code Playgroud)
这意味着gcc理解SpFunc是一种函数类型.
Joh*_*itb 44
您不能使用typedef为函数类型定义函数.它被明确禁止 - 参见6.9.1/2和相关的脚注:
在函数定义中声明的标识符(函数的名称)应具有函数类型,如函数定义的声明符部分所指定的那样.
目的是函数定义中的类型类别不能从typedef继承:
Run Code Online (Sandbox Code Playgroud)typedef int F(void); // type F is "function with no parameters // returning int" F f, g; // f and g both have type compatible with F F f { /* ... */ } // WRONG: syntax/constraint error F g() { /* ... */ } // WRONG: declares that g returns a function int f(void) { /* ... */ } // RIGHT: f has type compatible with F int g() { /* ... */ } // RIGHT: g has type compatible with F F *e(void) { /* ... */ } // e returns a pointer to a function F *((e))(void) { /* ... */ } // same: parentheses irrelevant int (*fp)(void); // fp points to a function that has type F F *Fp; //Fp points to a function that has type F
| 归档时间: |
|
| 查看次数: |
29084 次 |
| 最近记录: |