如何声明返回函数指针的函数?

4

想象一个带有double和int参数的函数myFunctionA:

myFunctionA (double, int);

这个函数应该返回一个函数指针:
char (*myPointer)();

我该如何在C语言中声明这个函数?

4个回答

12

typedef是你的好朋友:

typedef char (*func_ptr_type)();
func_ptr_type myFunction( double, int );

4
void (*fun(double, int))();

根据right-left-rulefun是一个返回指向具有不确定参数并返回void的函数的指针的double,int函数。

编辑:这里是该规则的另一个链接。

编辑2:此版本仅为了紧凑展示和证明确实可以完成。

在这里使用typedef确实非常有用。但不是针对指针,而是针对函数类型本身。

为什么?因为可以将其用作一种原型,以确保函数确实匹配。并且因为指针的标识仍然可见。

所以一个好的解决方案是:

typedef char specialfunc();
specialfunc * myFunction( double, int );

specialfunc specfunc1; // this ensures that the next function remains untampered
char specfunc1() {
    return 'A';
}

specialfunc specfunc2; // this ensures that the next function remains untampered
// here I obediently changed char to int -> compiler throws error thanks to the line above.
int specfunc2() {
    return 'B';
}

specialfunc * myFunction( double value, int threshold)
{
    if (value > threshold) {
        return specfunc1;
    } else {
        return specfunc2;
    }
}

谢谢您编辑它,但我已经给了您接受和+1。那正是我要寻找的。 - Martin Thoma
谢谢。我只是想要 a)表明清楚和 b)给出良好实践的提示。 - glglgl

3

创建一个typedef:

typedef int (*intfunc)(void);

int hello(void)
{
    return 1;
}

intfunc hello_generator(void)
{
    return hello;
}

int main(void)
{
    intfunc h = hello_generator();
    return h();
}

0
char * func() { return 's'; }

typedef char(*myPointer)();
myPointer myFunctionA (double, int){ /*Implementation*/ return &func; }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接