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?
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 + '();');
No, you can't assign values to functions.
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.
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.
switch(whichFunction) {
case 1: function1(); break;
case 2: function2(); break;
case 3: function3(); break;
}
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