How can I call a function using a function pointer?

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

    You declare a function pointer variable for the given signature of your functions like this:

    bool (* fnptr)();
    

    you can assign it one of your functions:

    fnptr = A;
    

    and you can call it:

    bool result = fnptr();
    

    You might consider using typedefs to define a type for every distinct function signature you need. This will make the code easier to read and to maintain. i.e. for the signature of functions returning bool with no arguments this could be:

    typdef bool (* BoolFn)();
    

    and then you can use like this to declare the function pointer variable for this type:

    BoolFn fnptr;
    

提交回复
热议问题