This is the reason why some people does not like pointers in C and C++. See my explanation below in your program:-
#include<iostream.h>
# include <conio.h>
void main()
{
clrscr();
int sum(int(*)(int),int);// Here first parameter in `sum` is a pointer to a function which return type is int. `int(*)(int)` here int(*) is function pointer and (int) is its parameter type.
int square(int);
int cube(int);
cout<<sum(square,4)<<endl;// Now you are passing address of function `square` as first parameter and its parameter 4, like square(4)
cout<<sum(cube,4)<<endl; // Here you are passing address of function `cube` as parameter and 4 as parameter to cube function
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i); //This `ptr` is nothing but the address of function passed to sum
//hence it execute like below
//When you are calling function `sum` with function pointer `square` as first parameter
//it execute like `s = s + square(i);`
//Now at the second call to `sum` it execute like `s = s + cube(i);`
}
return s;
}
solved Working of function pointers [closed]