How to call a function by it's ending number in the name

Hello, I have a stupid question, but I couldn't find the answer, how do I call a function by it's number at the end of the name, which is a variable number? (Without declaring a new array)

Below I have several functions: model1, model2, model3 ..., and I wand to make a random function that is calling the other functions randomly.

void model4()  //model 4
{  
  timp1=1;  
  timp2=5; 
}
void model5()  //model 5
{  
  timp1=5;  
  timp2=1; 
}
void model6()
{
  timp1=5;  
  timp2=5; 
}
void model7()
{
  randNumber = random(0,6);  
  k=0;
  if (k<10)
  {  
   **model(sprintf(randNumber))();**
  k++;
  }
   
}

Hello,

Why don't you just simply assign random values to timp1 and timp2?

timp1 = random(0,6);  
timp2 = random(0,6);

If you are just looking for the method for the random function call, I think you have to declare an array of function pointers (each pointing to one of the desired function) and then select an element randomly from this array.

This might help: How can I use an array of function pointers?

You can't do any manipulation of function names at runtime - they no longer exist in the code. Pointers to functions could help as @amazed suggested. Otherwise, just do it the long way with a switch.

Looks like a case for switch...case
https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/

void model7()
{
  randNumber = random(0,6);  
  for (k=0; k<10; k++)
  {
    switch (randNumber)
    {
      case 4: model4(); break;
      case 5: model5(); break;
      case 6: model6(); break;
    }
  }
}

Ok, thank you, I taught I was missing a simple but important command in C, but I will definitely insert a switch command. Thanks!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.