How can I use an array of function pointers?

前端 未结 10 1147
别那么骄傲
别那么骄傲 2020-11-22 17:24

How should I use array of function pointers in C?

How can I initialize them?

10条回答
  •  遇见更好的自我
    2020-11-22 17:32

    This "answer" is more of an addendum to VonC's answer; just noting that the syntax can be simplified via a typedef, and aggregate initialization can be used:

    typedef int FUNC(int, int);
    
    FUNC sum, subtract, mul, div;
    FUNC *p[4] = { sum, subtract, mul, div };
    
    int main(void)
    {
        int result;
        int i = 2, j = 3, op = 2;  // 2: mul
    
        result = p[op](i, j);   // = 6
    }
    
    // maybe even in another file
    int sum(int a, int b) { return a+b; }
    int subtract(int a, int b) { return a-b; }
    int mul(int a, int b) { return a*b; }
    int div(int a, int b) { return a/b; }
    

提交回复
热议问题