How would I make a function that takes address of another function as a parameter so that passing it is not necessary.
My first solution was this:
void empty_func() {}
void func(void (*additional_func) () = &empty_func)
{
additional_func();
// some other code...
}
This solution works.
However, I was wondering is there some more convenient way to make passing additional_function optional, so I do not have to make a new function (empty_func()) and passing it as a default argument?
As function pointers are also a pointer and null-equivalent for pointer types are
nullptrso you can assign the value to this default parameter asnullptr.Also, don't miss forget to add
nullptrcheck before using it.Also, it is more convenient to define an alias for this function-pointer as use like following:
But it is best to use features from
functionalheader file instead of these raw-function-pointers. Following is an example to achieve this usingfunctionalheader file:Output: