我希望得到一些帮助来理解为什么函数定义和函数指针返回类型需要按以下方式编写。
int ( * functionFactory (int n) ) (int, int) { Function Body }
函数定义取自C 中的函数指针如何工作?
这就是我想象的每个部分的含义。
returned function's | function Returns | | called function's | returned function's
return type | a function pointer | name of function | arguments | arguments
| | | | |
_V_ _V_ ____________________V________ _______V_ _V______
| | | | | | | | | |
int ( * functionFactory (int n) ) (int, int) { Function Body }
但是为什么它不写得更像一个普通函数,像这样在开头就将返回类型全部放在一起。
return type name of function arguments
| | |
_____V_________ _____V_______ ___V_
| | | | | |
int (*)(int, int) functionFactory (int n) { Function Body }
这是C语法原则“声明镜像使用”的神器。
给定一个声明
int ( * functionFactory (int n) ) (int, int)
,您可以使用它的一种方法是
int result = (*functionFactory(42))(123, 456);
为了使用参数 42 调用工厂,然后立即使用 123, 456 调用结果指针。
现在,在现实生活中实际使用这样的声明通常是不好的做法,因为它会被广泛认为不可读。相反,通常的建议是使用 typedef:
typedef int (*fptr_t)(int, int);
fptr_t functionFactory(int n) { … }
我建议使用函数类型。
typedef int myfunction(int,int);
myfunction *functionFactory(int n)
{
/* the code */
}