a pointer to a function ?

Hi, this code is confusing me, I think the code is illegal, but it can works. Can any body explains it for me? thx in advance!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

bool fncomp (int lhs, int rhs) {return lhs<rhs;}

struct classcomp {
  bool operator() (const int& lhs, const int& rhs) const
  {return lhs<rhs;}
};

int main ()
{
  ...
  bool(*fn_pt)(int,int) = fncomp; //what this line means?
  ...
  return 0;
}
closed account (S6k9GNh0)
It is very possible to assign a pointer to a function.
For the longest time I didn't believe this was possible and if it was, I thought it was a hack. But it's very legal and very common and legit practice!

http://www.newty.de/fpt/index.html

Though I understand them, I'd very well rather want you to read a mature and somewhat professionally authorized article.
Last edited on
bool(*fn_pt)(int,int) This declares that fn_pt is a pointer to a function that takes two integer type parameters and returns a bool type.

bool(*fn_pt)(int,int) = fncomp; We declare the function pointer and initialise it
with the adress of the fncomp function. (In C/C++, the name of a function is the address of the function.)

To call a function through a function pointer we can do it two ways:

1
2
3
  
bool result;
  result = (*fn_pt)(1,2); 


OR
1
2
bool result;
  result = fn_pt(1,2);


EDit:
please also note that you can also say:
bool(*fn_pt)(int,int) = &fncomp; when assigning the address of a function to a function pointer
Last edited on
Topic archived. No new replies allowed.