passing a function to another function

Hi everyone,

i want to create some generic code that only runs a function once so i don't have to keep creating new flags and variables.

i was hoping for something like this:

runOnce(randomFunction());

this would automatically run that function one time and then store that it had been run,

then

reset (randomFunction());

allows the function to be run again next time runOnce() is called.

now all of this is easy enough to do with flags, but i wanted to make something more dynamic that can automatically create variables for each task that is passed to it.

is there a way to do this?

thanks!

runOnce(randomFunction());That would call randomFunction, and pass its return value to runOnce.

What you want is runOnce(randomFunction);

Google "C function pointers"

Why are you needing to do this? Perhaps you aren't using idempotency where it would be useful?

AWOL:
runOnce(randomFunction());That would call randomFunction, and pass its return value to runOnce.

What you want is runOnce(randomFunction);

Google "C function pointers"

thanks for the tip i will check that out now!

I’ve done something similar here (but many others have also done similar things): it calls a random function (out of 11) by using a array of function pointers.

#define N_ANIM 11
void (*animation[])(CRGB couleur) = {anim1, anim2, anim3, anim4, anim5,
                                     anim6, anim7, anim8, anim9, anim10,
                                     anim11
                                    };
void loop() {
  int numAnim = random(N_ANIM); // <-- random selection of the function
  int numCoul = random(N_COUL);  //  <-- argument of the function
  animation[numAnim](couleur[numCoul]);  // <-- calls the selected function
}

All functions must be declared identically :

void anim5 (CRGB color) {
// whatever
}

void anim9 (CRGB color) {
// whatever
}

MarkT:
Why are you needing to do this? Perhaps you aren't using idempotency where it would be useful?

almost certainly, i am self taught in C++ so there is a lot of holes in my knowledge, what would be the best way to run functions once without having to manually create a flag variable for each routine?

What would be the value of avoiding the use of a simple flag system?

To my mind it is much easier to debug a simple system when it breaks. (Note the use of WHEN :slight_smile: )

…R

You could do it with an array of pointers to functions, possibly an array of structs, each of which contains a pointer to a function and its flag. Plausible design, I can see doing something similar if I were building a pinball table perhaps.

But why in this case? Do you have a concrete example of where this would be helpful or simplify your code? Or is this a theoretical exercise?