While listening through Stanford's Programming Abstractions course, I come across some piece of code that looks like the following.
void plot(double start, double end, double (fn)(double)) {
double i;
for (i = start; i <= end; i += 1)
printf("fn(%f) = %f\n", i, fn(i));
}
double plus1(double x) {
return x + 1;
}
int main(void) {
plot(1, 10, plus1);
return 0;
}
I compiled the code on my system using GCC, then G++; they both run perfectly.
I know that passing an int i = 2
into a function such as void func1(int a)
will make a new copy of that i
for that function while passing &i
to void func2(int *a)
will only give the function func2
the address of i
.
So can anyone explain to me what is the mechanism for passing fn
to plot
and how it differs from passing a function pointer as parameter?
There is absolutely no difference between void foo(double fn(double))
and void foo(double (*fn)(double))
. Both declare functions which take a pointer to a function as a parameter.
This is similar to how there is no difference between void bar(double arr[10])
and void bar(double* arr)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With