// pointer to functions
#include <iostream>
usingnamespace std;
int addition (int a, int b)
{ return (a+b); }
int subtraction (int a, int b)
{ return (a-b); }
int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}
int main ()
{
int m,n;
int (*minus)(int,int) = subtraction;
m = operation (7, 5, addition);
n = operation (20, m, minus);
cout <<n;
return 0;
}
If this: int (*minus)(int,int) = subtraction;
means that *minus=subtraction and minus=&subtraction, doesn't it mean that when you call int operation (int x, int y, int (*functocall)(int,int))
with n = operation (20, m, minus); //m=12;
that *functocall=&subtraction and functocall=&minus and when you g = (*functocall)(x,y);
you should get nonsense. shouldn't you? How can you call &subtraction? Why do you not have to use a pointer of depth 2?
The function is stored in memory just like any other variable. When you pass 2 numbers to that memory address (&subtraction), you get an integer in that memory address as the return value. So, you're actually getting the result of subtraction in the memory address &subtraction, you're not calling &subtraction.
You're confused just because of the name "function pointers". The pointer points actually at the return value of the function.
The dilemma is that he is misunderstanding how parameters are passed.
1 2 3 4 5 6 7
void func( int param );
int main()
{
int var = 5;
func(var); // is like saying 'param = var'
}
This does not change for function pointers:
1 2 3 4 5 6 7
int operation (int x, int y, int (*functocall)(int,int));
int main()
{
int (*minus)(int,int) = subtraction;
operation(x,y, minus); // is like saying 'functocall = minus'
}
since minus = &subtraction
and since functocall = minus
this means functocall = &subtraction
which means (*functocall)(...) will call subtraction
why isn't then minus=subtraction? Are the parameters passed differently when they are passed to functions? operation(x,y, minus); // is like saying 'functocall = minus'
isn't passed the same way as int (*functocall)(int,int)=minus; and int (*minus)(int,int) = subtraction;?
Because C was inconsistent about function pointer syntax. With [global] function pointers, the '&' is optional. Don't ask me why... it really bugs me.
1 2 3 4 5
// this...
int (*minus)(int,int) = subtraction;
// ...is the same as this...
int (*minus)(int,int) = &subtraction;
Personally I prefer to put the & in there to be consistent (and because it's required for "C++ style" or member function pointers), but since you weren't doing it here I didn't do it in my examples.
But yeah this is just a stupid thing the language does.
EDIT:
To clarify further, afaik, the above inconsistency is true for function names only.
That is... subtraction and &subtraction are the same only because subtraction is an actual function name. On the other hand, minus and &minus would be different because minus is a function pointer, not a function name.