问题描述
我一直在阅读有关函数作为参数的函数,特别是在C中,它们使用函数指针。假设我想实现牛顿raphson方法(以一种简单的方式)计算非线性方程中的零点。
参数 f 是派生和 newton_raphson 中的指针函数。
double derivative(double f(double),double x){...}
完全等价于
double derivative( double(* f)(double),double x){...}
只有前者看起来更好 - 通常当你可以省略括号时,你应该这样做。毕竟它们都相当于
double((((derivative)))(double(((*(f) )))(double((trouble))),double((x)))){...}
我希望只能在IOCCC中使用。然而,如果你声明,定义一个变量(不是函数参数),你需要使用
double(* f)(double);
as
double f(double);
仅仅是一个函数声明。
6.7.6.3函数声明符(包括原型) C11 draft n1570说:
和
6.9.1函数定义进一步说明那么
另外它有以下例子:
I have been reading about having functions with functions as parameters, and particulary in C, they use function pointers. Let's suppose I want to implement the newton raphson method (in a simple way) for computing zeros in non linear equations.
double derivative(double f(double), double x) { double h = 1e-9; return (f(x + h) - f(x)) / h; } double newton_raphson(double f(double), double x0, double tol) { double xk, diff; do { xk = x0 - f(x0) / derivative(f, x0); diff = fabs(xk - x0); x0 = xk; } while (diff >= tol); return xk; }So, to compute an approximation for derivative I need a function that returns a double and takes a double as an argument. Same for computing a root of the function, given the other parameters. My question is, why is this different from declaring function parameters as function pointers? For instance declaring the input parameter f as a function pointer instead of just a function...
解决方案The parameter f is a pointer-to-function in both derivative and newton_raphson.
double derivative(double f(double), double x) { ... }is exactly equivalent to
double derivative(double (*f)(double), double x) { ... }Only, the former looks nicer - usually when you can omit parentheses, you should probably do so. After all both of them are equivalent to
double ((((derivative)))(double (((*(f))))(double ((trouble))), double ((x)))) { ... }That I hope will only ever be used in IOCCC.
However, if you're declaring, defining a variable (not a function parameter), you need to use
double (*f)(double);as
double f(double);is just a function declaration.
6.7.6.3 Function declarators (including prototypes) of C11 draft n1570 says:
And6.9.1 Function definitions further says that
additionally it has the following example:
这篇关于C为什么函数指针作为参数而不是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!