Good day .. new to C++ .. wondering if one could offer some insight/suggestions how I might achieve a desired goal.
I'd like to have a loop that within a number of functions are called, but where an event external to the loop causes the actual code executed by the function(s) changes. Hoping to accomplish without numerous select/case if/else etc.
Is it possible to pass a function "pointer" to a function ?
Pass a parameter to the code that is executed?
THANKS in advance for any assist you might offer !
You can absolutely use a pointer to a function to change the function that you will call at runtime. If you could post a simple example of your loop and how you want to modify which function you call we can help you figure out the syntax.
#include <iostream>
void func1(int a)
{
std::cout << "Function 1: " << a << std::endl;
}
void func2(int a)
{
std::cout << "Function 2: " << a << std::endl;
}
void execute_function(void(*function)(int), int param)
{
function(param);
}
int main()
{
execute_function(func1, 5);
execute_function(func2, 10);
return 0;
}
In this example we declare a function called execute_function that will execute a function taking an int as parameter. In our main function, we the call this function with either func1 or func2. This example will produce the result: