MrOrdinaire
MrOrdinaire

Reputation: 165

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?

Upvotes: 6

Views: 273

Answers (2)

for1096
for1096

Reputation: 158

sorry for my mistake.

void foo(int (fn)(int)){}
void bar(int (*fn)(int)){}

compile above code like this:

gcc -S sample.c

you will find that there's no difference. just different coding style.

you may try to compile and run this code as well:

#include <stdio.h>
void foo(int (fn)(int))
{
    printf("foo: %x.\n",fn);
}
void bar(int (*fn)(int))
{
    printf("bar: %x.\n",fn);
}
int main(int argc)
{
    foo(main);
    bar(main);
    return 0;
}

Upvotes: 0

Mankarse
Mankarse

Reputation: 40603

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

Upvotes: 7

Related Questions