返回函数指针类型

S E*_*S E 54 c syntax types function-pointers

我经常发现需要编写返回函数指针的函数.每当我这样做,我使用的基本格式是:

typedef int (*function_type)(int,int);

function_type getFunc()
{
   function_type test;
   test /* = ...*/;
   return test;
}
Run Code Online (Sandbox Code Playgroud)

但是,在处理大量函数时,这会很麻烦,所以我不想为每个函数声明一个typedef(或者对于每个函数类)

我可以删除typedef并声明函数中返回的局部变量: int (*test)(int a, int b);使函数体看起来像这样:

{
     int (*test)(int a, int b);
     test /* = ...*/;
     return test;
}
Run Code Online (Sandbox Code Playgroud)

但后来我不知道该函数的返回类型设置了什么.我试过了:

int(*)(int,int) getFunc()
{
    int (*test)(int a, int b);
    test /* = ...*/;
    return test;
}
Run Code Online (Sandbox Code Playgroud)

但是报告语法错误.如何在不声明函数指针的typedef的情况下声明此类函数的返回类型.它甚至可能吗?另请注意,我知道为每个函数声明typedef似乎更干净,但是,我非常小心地将我的代码构造成尽可能干净且易于遵循.我想消除typedef的原因是它们通常只用于声明检索函数,因此在代码中看起来是多余的.

Eri*_*hil 60

int (*getFunc())(int, int) { … }
Run Code Online (Sandbox Code Playgroud)

这提供了您要求的声明.另外,正如ola1olsson指出的那样,最好插入void:

int (*getFunc(void))(int, int) { … }
Run Code Online (Sandbox Code Playgroud)

这说明getFunc可能不会采取任何参数,这可以帮助避免错误,如有人无意中写getFunc(x, y)而不是getFunc()(x, y).

  • 好答案.但完全是braindead C函数指针语法. (3认同)
  • 可能偏离主题,但是,使用[顺时针/螺旋规则](http://c-faq.com/decl/spiral.anderson.html)很容易评估复杂的函数声明 (2认同)

yos*_*sim 5

您可以做以下事情:

int foo (char i) {return i*2;}

int (*return_foo()) (char c)
{
   return foo;
}
Run Code Online (Sandbox Code Playgroud)

但是上帝,我希望我永远不必调试你的代码....

  • 哎呦!再读一遍,这有点粗鲁,对不起,我不是那么说的意思 - 这只是一个笑话. (5认同)