How can I call a function using a function pointer?

前端 未结 16 1668
孤独总比滥情好
孤独总比滥情好 2020-12-02 17:24

Suppose I have these three functions:

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

How do I call one of these functions conditionally using a function poi

16条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 17:28

    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])()
      {
        ...
      }
      ...
    }
    

提交回复
热议问题