I have a recurring problem that when I'm controlling leds, I make several different functions for different fx and just want to trigger them randomly but having a hard time to formulate it in an intelligent way and end up hardcoding every function call.

ex: I have let's say 10 functions called anim1();, anim2();, anim3(); etc and would like to called them randomly in that fashion :

randNumber = random(1,11);
anim[randNumber]();

I know that it's not that type of brackets I need to use but I can't find the proper syntax and I'm wondering if it's possible to do that.. I'm sure there must be a way ;)

thanks for your help

share|improve this question

What you want is an array of function pointers.

void anim1() {
    // blah blah
}

void anim2() { 
    // blah blah
}
// ... etc ...

typedef void (*animptr)();

animptr anims[10] = {
    anim1,
    anim2,
    anim3,
    // ... etc ...
    anim10
};

Then you can use:

anims[animNumber]();
share|improve this answer
    
You mean typedef void (*animptr)();. – Edgar Bonet May 21 at 12:42
    
Yes, I do. Thanks for spotting that. – Majenko May 21 at 12:43
    
I didn't know this was possible. But I think I would feel dirty when using it. It just seems wrong to do this. – Gerben May 21 at 13:46
    
Why so? Function pointers are one of the most powerful facilities of C. Imagine trying to implement callbacks without being able to use function pointers - and an array of them is just an extension of that. A function is, after all, just a location in memory... – Majenko May 21 at 13:47
    
thanks so much Majenko! exactly what i was looking for! :D – robophil May 23 at 0:56

I end up using another way and just wanted to share it here for anybody that would want a bit less efficient but simpler way of doing that ;) it's cleaner with Majenko's solution for sure but this gets the job done and is pretty easy to understand and troubleshoot. cheers!

int randNumber;

void loop(){
randNumber = random(1,14);

if (button is pressed or something){
callAnim(randNumber);
}
}


void callAnim(int randNumber){
if (randNumber==1){
anim1();
}
if (randNumber==2){
anim2();
}
}
// ... etc ...

void anim1() {
// blah blah
}

void anim2() { 
// blah blah
}
// ... etc ...
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.