Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 643
zlack Avatar asked Nov 18 '09 19:11

zlack


1 Answers

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);
}
like image 195
Joy Dutta Avatar answered Sep 17 '22 14:09

Joy Dutta