问题描述
想象一下,一个功能与myFunctionA参数双和int:
myFunctionA(双,INT);
这个函数返回一个函数指针:
字符(* myPointer)();
我如何用C声明此功能?
无效(*乐趣(双,INT))();
按照是另一个链接到该规则
编辑2:此版本仅适用于紧凑的缘故并表明它确实可以做到
这的确是在这里使用一个typedef有用。但不是指针,但以函数类型本身
为什么呢?因为它是可以使用它作为一种原型的话,因此保证了功能做的非常匹配。而由于身份为指针仍然可见。
所以一个好的解决方案是
的typedef CHAR specialfunc();
specialfunc * myFunction的(双,INT);specialfunc specfunc1; //这确保了一个功能仍然未被篡改
CHAR specfunc1(){
回归'A';
}specialfunc specfunc2; //这确保了一个功能仍然未被篡改
//我在这里乖乖的改焦炭为int - >编译器会引发错误由于上面的行。
INT specfunc2(){
回归'B';
}specialfunc * myFunction的(双重价值,诠释阈值)
{
如果(价值>阈值){
返回specfunc1;
}其他{
返回specfunc2;
}
}
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?
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;
}
}
这篇关于我如何声明返回函数指针的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!