How can I call a function using a function pointer?

前端 未结 16 1459
孤独总比滥情好
孤独总比滥情好 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])()
      {
        ...
      }
      ...
    }
    
    0 讨论(0)
  • 2020-12-02 17:28

    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!

    0 讨论(0)
  • 2020-12-02 17:30
    bool (*FuncPtr)()
    
    FuncPtr = A;
    FuncPtr();
    

    If you want to call one of those functions conditionally, you should consider using an array of function pointers. In this case you'd have 3 elements pointing to A, B, and C and you call one depending on the index to the array, such as funcArray0 for A.

    0 讨论(0)
  • 2020-12-02 17:30

    The best way to read that is the clockwise/spiral rule by David Anderson.

    0 讨论(0)
  • 2020-12-02 17:31

    I usually use typedef to do it, but it may be overkill, if you do not have to use the function pointer too often..

    //assuming bool is available (where I come from it is an enum)
    
    typedef bool (*pmyfun_t)();
    
    pmyfun_t pMyFun;
    
    pMyFun=A; //pMyFun=&A is actually same
    
    pMyFun();
    
    0 讨论(0)
  • 2020-12-02 17:32

    Calling a function through a function pointer

    float add(int, float), result;
    
    int main()
    {
        float (*fp)(int, float);
        float result;
        fp = add;
        result = add(5, 10.9);    // Normal calling
        printf("%f\n\n", result);
    
        result = (*fp)(5, 10.9);  // Calling via a function pointer
        printf("%f\n\n", result);
    
        result = (fp)(5, 10.9);   // Calling via function pointer. The
                                  // indirection operator can be omitted
    
        printf("%f", result);
        getch();
    }
    
    float add(int a, float b)
    {
        return a+b;
    }
    

    >

    Output

    15.90000
    15.90000
    15.90000
    
    0 讨论(0)
提交回复
热议问题