Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function depending on a variable?

Tags:

c++

Can you call a function depending on which number an integer is?

Here's what I mean:

#include <iostream>

using namespace std;

int whichFunction;

int main()
{
    cout << "Which function do you want to call?";
    cin >> whichFunction;

    function[whichFunction](); 
    //If you entered 1, it would call function1 - same with 2, 3
    //or Hihihi (of course only when whichFunction would be a string)
}


void function1()
{
    cout << "Function No. 1 was called!";
}

void function2()
{
    cout << "Function No. 2 was called!";
}

void functionHihihi()
{
    cout << "Function Hihihi was called!";
}

I know this doesn't work but I hope you get the idea.

So is there a way to do something like that?

like image 855
TPRammus Avatar asked Sep 11 '16 11:09

TPRammus


People also ask

How do you call a function as a variable?

This also should allow you to pass in arguments: eval('var myfunc = ' + variable); myfunc(args, ...); If you don't need to pass in arguments this might be simpler. eval(variable + '();');

Is it possible to assign a value to a function call?

No, you can't assign values to functions.

What do you call the variables during function call?

Calling a Function The variables within the function which receive the passed data are referred to as the "formal" parameters. The formal parameters are local variables, which exist during the execution of the function only, and are only known by the called function.


2 Answers

Yes, there is a way to do that.

//Array for the functions
std::array<std::function<void()>, 3> functions = { &function1, &function2, &function3 };

//You could also just set them manually
functions[0] = &function1;
functions[1] = &function2;
functions[2] = &function3;

Then you can use it as a normal array:

functions[whichFunction](); //Calls function number 'whichFunction'

Do note that the functions all have to have the same signature.


If you do not want to use std::function for some reason, you can use function pointers.

like image 129
Rakete1111 Avatar answered Oct 14 '22 01:10

Rakete1111


switch(whichFunction) {
    case 1: function1(); break;
    case 2: function2(); break;
    case 3: function3(); break;
}
like image 35
Pete Becker Avatar answered Oct 14 '22 01:10

Pete Becker