c++ pass function as argument

#include <iostream>
using namespace std;

// Function that takes a function pointer as an argument
void callerFunction(void (*functionPtr)(int)) {
    // Calling the function passed as an argument with value 5
    functionPtr(5);
}

// Sample function to be passed as an argument
void sampleFunction(int value) {
    cout << "Value passed to sampleFunction: " << value << endl;
}

int main() {
    // Passing sampleFunction as an argument to callerFunction
    callerFunction(sampleFunction);

    return 0;
}

Explanation:

  • #include <iostream>: Includes the Input/Output stream library to perform input/output operations.
  • using namespace std;: Allows the use of objects and functions from the standard C++ library.
  • void callerFunction(void (*functionPtr)(int)): Defines a function named callerFunction that takes a function pointer functionPtr as an argument. This function pointer points to a function that takes an integer argument and returns void.
  • functionPtr(5);: Invokes the function whose pointer is passed as an argument with the value 5.
  • void sampleFunction(int value): Defines a sample function sampleFunction that takes an integer argument value and prints it to the standard output.
  • int main(): The starting point of the program.
  • callerFunction(sampleFunction);: Calls callerFunction and passes sampleFunction as an argument. This means sampleFunction will be executed within callerFunction with the value 5.
  • return 0;: Indicates successful termination of the main() function.