I just learn about passing a function as an argument in C ++, however I wonder what its meaning is.
Given 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 do I need to pass the Function argument as a parameter to 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 standard C qsort library function , which has a 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 writing an entire new sorting function for each type of sorting to be performed.
, C qsort, , . , , , , , , ..
qsort
, , , . , (, , ++, ).
, . qsort , . , , , .
, , . , , viewport/canvas . , , .
, , - ( - , ). , : " !" , , , , .
++ , , , , , , , - , , .. .