How to call the function using function pointer?

2019-01-22 07:11发布

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?

15条回答
SAY GOODBYE
2楼-- · 2019-01-22 07:44
//Declare the pointer and asign it to the function
bool (*pFunc)() = A;
//Call the function A
pFunc();
//Call function B
pFunc = B;
pFunc();
//Call function C
pFunc = C;
pFunc();
查看更多
不美不萌又怎样
3楼-- · 2019-01-22 07:46

This has been more than adequately answered, but you may find this useful: The Function Pointer Tutorials. It is a truly comprehensive treatment of the subject in five chapters!

查看更多
等我变得足够好
4楼-- · 2019-01-22 07:50

Slightly different approach:

bool A() {...}
bool B() {...}
bool C() {...}

int main(void)
{
  /**
   * Declare an array of pointers to functions returning bool
   * and initialize with A, B, and C
   */
  bool (*farr[])() = {A, B, C};
  ...
  /**
   * Call A, B, or C based on the value of i
   * (assumes i is in range of array)
   */
  if (farr[i]()) // or (*farr[i])()
  {
    ...
  }
  ...
}
查看更多
登录 后发表回答