getting a newbie off on the right foot ..

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 !
Last edited on
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.
You can pass a function pointer to a function, as long as you know the type of the function to be called beforehand. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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:

Function 1: 5
Function 2: 10
Last edited on
THANK YOU folks !! Sorry I didn't respond sooner, I failed to have notifications turned on.

APPRECIATE the assist
Topic archived. No new replies allowed.