How do I assign a function in a if-condition in C++?
Say I have the functions f1 and f2 (available and defined in the global environment), and some integer i.
I want to define a new function f3, which equals f1 if i = 1 and f2 otherwise. 
How to do this?
Pseudo-code of what I want:
if (i == 1)
{
    f3 = f1;
}
else 
{
    f3 = f2;
}
return f3(5);
                You can declare f3 as function pointer. You can use an alias or auto to make it simpler
using F = void(*)(int);
void f1(int) {}
void f2(int) {}
int main() {
    void(*f3)(int);
    F f4 = f1;
    auto f5 = f2;
    int i = 1;
    if (i == 1) {
        f3 = f1;
        f5 = f1;
    } else {
        f3 = f2;
        f4 = f2;
    }
    f3(5);
    f4(10);
    f5(15);
}
The name of a function can be used as a pointer: f1 == &f1
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