I am studying a C++ tutorial. I can’t understand this example on Pointers to Functions.
Here it is:-
// pointer to functions
#include <iostream>
using namespace 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;
}
The lines “m = operation (7, 5, addition);” and “n = operation (20, m, minus);” are treated the same way, but while minus has been declared as a pointer to function, addition hasn’t. So, how did they both work the same way?
The type of
additionisint (&)(int,int)which can decay into a pointer of typeint (*)(int,int)which is same as that ofoperationfunction’s third parameter. So you can passadditionas third argument to the functionoperation.The type of
subtractionis also the same as that ofaddition. In your code, the address ofsubtractionis first stored as local variable of the compatible type, and then that variable is passed as argument tooperationfunction.In case of
addition, it’s address is not stored as local variable, instead its passed as such tooperation. Its initializing the function’s third parameter directly with the function’s address, without using any local variable.A conversion from
int (&)(int,int)toint (*)(int,int)occurs in both cases. Its just that withsubstration, the conversion occurs when initializing the local variable, and withaddition, the conversion occurs when initializing the function parameter.An analogy would be this:
Note the type of
100isint, so it first converts todoubletype, which is then stored as local variablex, which in turn is passed to the functionfas first argument. And the second argument100is passed directly to the function, so even now it first converts todoubleand then it initializesb(the second parameter of the function).Again, a conversion from
inttodoubleoccurs in both cases. Its just that first argument conversion occurs when initializing the local variablex, and second argument conversion occurs when initializing the second parameter of the function.