Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign function in if condition?

Tags:

c++

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);
like image 374
Janus Avatar asked Dec 05 '22 09:12

Janus


1 Answers

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

like image 135
Thomas Sablik Avatar answered Dec 21 '22 22:12

Thomas Sablik