I am making C game-project and in the game I need to choose random bonuses(functions).
(below is the example of the code)
void triple_balls(){
...
}
void longer_paddle(){
...
}
void shorter_paddle(){
...
}
void bonus_activator(){
//Here I must choose one of the 3 functions above
//FIXME
}
CodePudding user response:
Use a function pointer array instead
using BonusFunc = void (*)();
BonusFunc[3] = { triple_balls, longer_paddle, shorter_paddle };
void bonus_activator(){
BonusFunc[rand() % 3](); // just an example, don't use rand() in real code
}
CodePudding user response:
You can use std::function
, to store you functions in a container.
Then create an array of std::function
of size 3
.
#include <functional>
#include <iostream>
void triple_balls() { /* YOUR CODE */ }
void longer_paddle() { /* YOUR CODE */ }
void shorter_paddle() { /* YOUR CODE */ }
void bonus_activator(){
std::function<void(void)> farr[3] =
{
triple_balls,
longer_paddle,
shorter_paddle
};
farr[rand() % 3]();
}
CodePudding user response:
std::array{
&triple_balls,
&longer_paddle,
&shorter_paddle,
}
.at(rand() % 3)();
fits in only one-line and no variables needed and the optimizer will likely reduce this into a switch-statement-like operation:
std::array{ &triple_balls, &longer_paddle, &shorter_paddle }.at(rand() % 3)();