Function as parameter vs function pointer as parameter

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?

+6
source share
2 answers

There is absolutely no difference between void foo(double fn(double)) and void foo(double (*fn)(double)) . Both declare functions that take a function pointer as a parameter.

This is similar to how there is no difference between void bar(double arr[10]) and void bar(double* arr) .

+7
source

Sorry for my mistake.

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

compile the code above:

gcc -S sample.c

you will find that there is no difference. just a different coding style.

you can try to compile and run this code:

 #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; } 
0
source

Source: https://habr.com/ru/post/907635/


All Articles