Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 函数原型typedef可以在函数定义中使用吗?_C_Typedef_Function Declaration - Fatal编程技术网

C 函数原型typedef可以在函数定义中使用吗?

C 函数原型typedef可以在函数定义中使用吗?,c,typedef,function-declaration,C,Typedef,Function Declaration,我有一系列相同原型的函数 int func1(int a, int b) { // ... } int func2(int a, int b) { // ... } // ... 现在,我想简化它们的定义和声明。当然,我可以使用这样的宏: #define SP_FUNC(name) int name(int a, int b) 但是我想把它保存在C中,所以我尝试使用存储说明符typedef来实现: typedef int SpFunc(int a, int b); 这似乎对宣言起到

我有一系列相同原型的函数

int func1(int a, int b) {
  // ...
}
int func2(int a, int b) {
  // ...
}
// ...
现在,我想简化它们的定义和声明。当然,我可以使用这样的宏:

#define SP_FUNC(name) int name(int a, int b)
但是我想把它保存在C中,所以我尝试使用存储说明符
typedef
来实现:

typedef int SpFunc(int a, int b);
这似乎对宣言起到了很好的作用:

SpFunc func1; // compiles
但不是为了定义:

SpFunc func1 {
  // ...
}
这给了我以下错误:

error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
有没有正确的方法,或者说是不可能的? 就我对C语言的理解而言,这应该是可行的,但事实并非如此。为什么?


注意,gcc理解我要做的事情,因为如果我写

SpFunc func1 = { /* ... */ }
它告诉我

error: function 'func1' is initialized like a variable

这意味着gcc理解SpFunc是一种函数类型。

a
typedef
定义的是一种类型,而不是标题(即源代码文本)。如果需要计算出标题的代码,则必须使用
#define
(尽管我不建议这样做)


([编辑]第一种方法之所以有效,是因为它没有定义原型——它定义了一个由
typedef
定义的类型的变量,这不是您想要的。)

您不能使用函数类型的typedef定义函数。明确禁止-参考6.9.1/2和相关脚注:

功能定义中声明的标识符(即功能名称)应 具有函数定义的声明器部分指定的函数类型

其目的是函数定义中的类型类别不能从typedef继承:

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

不,这不是指针的类型。这将是
typedefint(*SpFunc)(inta,intb)。因为声明是有效的,所以它是一个合适的函数类型。问题是为什么我不能用它来定义。对不起,没有看到缺少星号。谢谢你的更正。这是对什么的回应?这是页面上唯一提到的“标题”。@JimBalter:这是对问题的回答。他试图使用typedef作为函数头。我说这是不可能的,因为typedef定义的是类型,而不是标题。在你的回答中,你写了“标题(这是源代码文本)”——这是C中的用法,但与这个问题无关。现在你说“函数头”。。。在C中没有这样的函数,但您可能指的是一个函数声明器。但你还是完全偏离了底线。。。OP知道SpFunc是一种类型(“这意味着gcc理解SpFunc是一种函数类型”),并且它不能用于定义函数(因为它会产生错误)。高铁的问题是为什么不,如果有其他的方法可以做到这一点。上面克里斯托夫的评论给出了正确的答案。我对此感到害怕。谢谢你的确认。这有什么道理吗?在我看来,这是一个有用的功能。@bitmask:函数可以共享一个typedef,但具有不同的命名参数-这些名称不是函数签名的一部分,如果声明不是定义的一部分,甚至可以省略