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

时间:2011-11-06 16:50:21

标签: c function-pointers

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

myFunctionA (double, int);

此函数应返回一个函数指针:

char (*myPointer)();

如何在C中声明此功能?

4 个答案:

答案 0 :(得分:12)

typedef是你的朋友:

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

答案 1 :(得分:4)

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

根据right-left-rulefundouble, int的函数,返回指向返回void的不确定参数的函数的指针。

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

编辑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;
    }
}

答案 2 :(得分: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();
}

答案 3 :(得分:0)

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

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