Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function as parameter vs function pointer as parameter

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?

like image 385
MrOrdinaire Avatar asked Feb 04 '12 09:02

MrOrdinaire


1 Answers

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).

like image 137
Mankarse Avatar answered Nov 17 '22 14:11

Mankarse