How do I declare a function that returns a function pointer?

烈酒焚心 提交于 2019-12-10 17:56:50

问题


Imagine a function myFunctionA with the parameter double and int:

myFunctionA (double, int);

This function should return a function pointer:

char (*myPointer)();

How do I declare this function in C?


回答1:


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

According to the right-left-rule, fun is a function of double, int returning a pointer to a function with uncertain parameters returning void.

EDIT: This is another link to that rule.

EDIT 2: This version is only for the sake of compactness and for showing that it really can be done.

It is indeed useful to use a typedef here. But not to the pointer, but to the function type itself.

Why? Because it is possible to use it as a kind of prototype then and so ensure that the functions do really match. And because the identity as a pointer remains visible.

So a good solution would be

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:


typedef is your friend:

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



回答3:


Make a 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();
}



回答4:


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

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


来源:https://stackoverflow.com/questions/8028623/how-do-i-declare-a-function-that-returns-a-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!