What are function pointers used for, and how would I use them?

前端 未结 9 2314
野趣味
野趣味 2020-11-29 06:51

I understand I can use pointers for functions.

Can someone explain why one would use them, and how? Short example code would be very helpful to me.

9条回答
  •  粉色の甜心
    2020-11-29 07:40

    A simple case is like this: You have an array of operations (functions) according to your business logic. You have a hashing function that reduces an input problem to one of the business logic functions. A clean code would have an array of function pointers, and your program will deduce an index to that array from the input and call it.

    Here is a sample code:

    typedef void (*fn)(void) FNTYPE;
    FNTYPE fn_arr[5];
    
    fn_arr[0] = fun1; // fun1 is previously defined
    fn_arr[1] = fun2;
    ...
    
    void callMyFun(string inp) {
        int idx = decideWhichFun(inp); // returns an int between 0 and 4
        fn_arr[idx]();
    }
    

    But of course, callbacks are the most common usage. Sample code below:

    void doLengthyOperation(string inp, void (*callback)(string status)) {
      // do the lengthy task
      callback("finished");
    }
    
    void fnAfterLengthyTask(string status) {
        cout << status << endl;
    }
    
    int main() {
        doLengthyOperation(someinput, fnAfterLengthyTask);
    }
    

提交回复
热议问题