'In C++, coding for Arduino, how can I save a function to a variable and call it later via the variable?
I want to save a function I've made to a string variable and call it later via the variable - something like this:
String hello = "helloWorld();";
void loop()
{
hello;
}
void helloWorld()
{
//does functional things...
}
This is a super basic idea of what I want to make happen. I'm making a game and want a certain function (different every time) to be stored in a variable to be played back later.
Solution 1:[1]
To declare a function pointer, you need to know its signature.
If your function helloWorld does not take parameters and returns nothing (void
), a variable to store that could be defined as
void (*myFunc)() = helloWorld;
void loop()
{
myFunc();
}
The only Arduino specific is that usually the required function declaration is done for you secretly behind the scenes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
