Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to Functions (C++)

Tags:

c++

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?

like image 542
wajed Avatar asked Mar 20 '26 16:03

wajed


1 Answers

Using a function name as an argument parameter in a function call, or on the right-hand side of the assignment operator in C/C++, causes a conversion to a function pointer to the original function.

So for instance if you have a function like

void my_function(int a, int b);

If you use the identifier my_function on the right-hand side of the assignment operator like this:

void (*my_function_ptr)(int, int) = my_function;

Then my_function implicitly converts from a function object to a function pointer of type void (*)(int, int), initializing the identifier my_function_ptr so that it points to my_function. The same situation would also occur when passing my_function to another function like:

void another_function(int, void (*)(int, int));
another_function(5, my_function);

In the call to another_function(), the identifier my_function is again converted to a pointer to the original function.

Finally, keep in mind this only occurs if you simply pass the identifier name to a function argument, or put it on the right-hand side of the assignment operator. Adding a function call using the () symbols and an optional argument list (i.e., my_function(5, 6)) will evaluate the function, not cause a conversion to a function pointer.

like image 161
Jason Avatar answered Mar 23 '26 04:03

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!