I just learn about passing a function of as an argument in c++, however I wonder what is its significance.
Considering this example,
#include <iostream>
using namespace std;
void argumentFunction(int x) {
cout << x << " is the result.";
}
void myFunction(void (*functionparam) (int), char parameter[80]) {
cout << parameter;
(*functionparam)(1);
}
int main() {
myFunction(&argumentFunction, "I am calling a function with a function.");
cin.ignore(80,'\n');
return 0;
}
why would I need to pass argumentFunction as a parameter in myFunction, which in fact I can directly call it without passing it:
like this:
#include <iostream>
using namespace std;
void argumentFunction(int x) {
cout << x << " is the result.";
}
void myFunction(char parameter[80]) {
cout << parameter;
argumentFunction(1);
}
int main() {
myFunction( "I am calling a function with a function.");
cin.ignore(80,'\n');
return 0;
}
One example is in the C standard library function qsort, which has the signature:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
This allows the programmer to pass an arbitrary comparison function to the existing sorting algorithm instead of having to write a whole new sort function for each type of sorting that needs to be done.
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