While listening through the Stanford Programming Abstractions course, I come across some piece of code that looks like this.
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 work great.
I know that passing int i = 2
to a function like void func1(int a)
will make a new copy of this i
for this function, and passing &i
- void func2(int *a)
will only give the function func2
address i
.
So can anyone explain to me what the mechanism for passing fn
to plot
and how it differs from passing a function pointer as a parameter?
source share