How can I call a function using a function pointer?

前端 未结 16 1661
孤独总比滥情好
孤独总比滥情好 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:52

    Initially define a function pointer array which takes a void and returns a void.

    Assuming that your function is taking a void and returning a void.

    typedef void (*func_ptr)(void);
    

    Now you can use this to create function pointer variables of such functions.

    Like below:

    func_ptr array_of_fun_ptr[3];
    

    Now store the address of your functions in the three variables.

    array_of_fun_ptr[0]= &A;
    array_of_fun_ptr[1]= &B;
    array_of_fun_ptr[2]= &C;
    

    Now you can call these functions using function pointers as below:

    some_a=(*(array_of_fun_ptr[0]))();
    some_b=(*(array_of_fun_ptr[1]))();
    some_c=(*(array_of_fun_ptr[2]))();
    

提交回复
热议问题