Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ functions as parameters without pointers

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;
}
like image 488
a3920 Avatar asked Sep 27 '22 06:09

a3920


People also ask

Can I pass a function as a parameter in C?

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.

Can we use function as a parameter of another function?

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.

Do you have to free function pointers?

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.

Can a function have no parameters in C?

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.


1 Answers

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;
}
like image 193
cdonat Avatar answered Sep 30 '22 06:09

cdonat