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 namedcallerFunction
that takes a function pointerfunctionPtr
as an argument. This function pointer points to a function that takes an integer argument and returnsvoid
.functionPtr(5);
: Invokes the function whose pointer is passed as an argument with the value5
.void sampleFunction(int value)
: Defines a sample functionsampleFunction
that takes an integer argumentvalue
and prints it to the standard output.int main()
: The starting point of the program.callerFunction(sampleFunction);
: CallscallerFunction
and passessampleFunction
as an argument. This meanssampleFunction
will be executed withincallerFunction
with the value5
.return 0;
: Indicates successful termination of themain()
function.