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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With