When searching for how to pass functions as parameters in C++, I only find examples that use function pointers. However the following compiles and outputs "g20" as expected in Visual Studio. Is it better to declare f like this:
f(void (*fun)());
instead of
f(void fun());
my example:
#include <iostream>
using namespace std;
int f(void fun());
void g();
int main() {
cout << f(g);
}
void g() {
cout << "g";
}
int f(void fun()) {
fun();
return 20;
}
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.
You can use function handles as input arguments to other functions, which are called function functions. These functions evaluate mathematical expressions over a range of values.
You must not because free(ptr) is used only when pointer ptr is previously returned by any of malloc family functions. Passing free a pointer to any other object (like a variable or array element) causes undefined behaviour.
If a function takes no parameters, the parameters may be left empty. The compiler will not perform any type checking on function calls in this case. A better approach is to include the keyword "void" within the parentheses, to explicitly state that the function takes no parameters.
You might prefer std::function<>
instead of function pointers. It can not only store function pointers, but also lambdas, bind expressions, function objects (objects with operator()
), etc. Especially the lambdas will make your API a lot better usable.
int f(std::function<void()>& fun) {
fun();
return 20;
}
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