How can I call a function using a function pointer?

Priya picture Priya · Dec 23, 2009 · Viewed 110.6k times · Source

Suppose I have these three functions:

bool A();
bool B();
bool C();

How do I call one of these functions conditionally using a function pointer, and how do I declare the function pointer?

Answer

Abhineet picture Abhineet · Dec 23, 2009

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.