Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of passing a function as an argument

Tags:

c++

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;
}
like image 438
XDProgrammer Avatar asked Dec 19 '22 03:12

XDProgrammer


1 Answers

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.

like image 153
jangler Avatar answered Dec 21 '22 17:12

jangler