【发布时间】:2016-11-10 23:31:01
【问题描述】:
在How do function pointers in C work? 的答案之一中,一位用户解释了如何在返回值中使用函数指针。这是有问题的代码:
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
对我来说,你声明 functionFactory 函数的方式很奇怪——在我看来你混淆了返回类型(指向函数的指针)和函数名本身(functionFactory)。
例如,当我们编写一个返回其参数平方的简单函数时,我们会编写类似
int square(int n){
return n*n;
}
很明显,我们返回的类型在左边,然后我们写函数名,然后它接受什么参数。所以当我们返回一个指向函数的指针时,我们为什么不写这样的东西:
( int (*function)(int, int) ) functionFactory(int n) { ...
这里的返回类型(它是一个函数的指针)和它的细节(例如我们指向的函数返回什么以及它接受什么作为参数)在左边清楚地分开并且functionFactory函数本身的名称是在右边。对我来说,我的版本似乎更合乎逻辑和清晰,我们为什么不这样写呢?
【问题讨论】:
-
C 对声明符使用中缀表示法。这是根据“声明遵循使用”的原则。我们以
a[5]访问数组,因此它被声明为int a[5];,而不是int[5] a;。函数类型也是如此。 -
int (*function)(int, int) functionFactory(int n) { ..."这里是返回类型(这是一个指向函数的指针)" - 如果不是返回类型,那么该行中的第一个int是什么? -
您当然可以为这些函数指针声明 typedef,然后使用这些 typedef 的函数声明看起来更“正常”。