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

C 如何声明返回函数指针的函数?,c,function-pointers,C,Function Pointers,想象一个参数为double和int的函数myfunction: myFunctionA (double, int); 此函数应返回函数指针: char (*myPointer)(); 如何在C中声明此函数?typedef是您的朋友: typedef char (*func_ptr_type)(); func_ptr_type myFunction( double, int ); 制作一个typedef: typedef int (*intfunc)(void); int hello(vo

想象一个参数为double和int的函数myfunction:

myFunctionA (double, int);
此函数应返回函数指针:

char (*myPointer)();

如何在C中声明此函数?

typedef
是您的朋友:

typedef char (*func_ptr_type)();
func_ptr_type myFunction( double, int );
制作一个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();
}
根据fun是
double,int
的函数,返回指向函数的指针,该函数的参数不确定,返回
void

编辑:是指向该规则的另一个链接

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

谢谢你编辑它,但是我已经给了你accept和+1。那正是我要找的。我只是想a)澄清,b)给出良好实践的提示。
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;
    }
}
char * func() { return 's'; }

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