How can I call a function using a function pointer?
I think your question has already been answered more than adequately, but it might be useful to point out explicitly that given a function pointer
void (*pf)(int foo, int bar);
the two calls
pf(1, 0);
(*pf)(1, 0);
are exactly equivalent in every way by definition. The choice of which to use is up to you, although it's a good idea to be consistent. For a long time, I preferred (*pf)(1, 0)
because it seemed to me that it better reflected the type of pf
, however in the last few years I've switched to pf(1, 0)
.
Declare your function pointer like this:
bool (*f)();
f = A;
f();
You can do the following: Suppose you have your A,B & C function as the following:
bool A()
{
.....
}
bool B()
{
.....
}
bool C()
{
.....
}
Now at some other function, say at main:
int main()
{
bool (*choice) ();
// now if there is if-else statement for making "choice" to
// point at a particular function then proceed as following
if ( x == 1 )
choice = A;
else if ( x == 2 )
choice = B;
else
choice = C;
if(choice())
printf("Success\n");
else
printf("Failure\n");
.........
.........
}
Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.