Is it OK to have a loop()s array?

Hi all.

I have loopA(); loopB(); loopC(); loopD();

can I make: loopArray[] = {loopA(), loopB(), loopC(), loopD()};
and call each of by: loopArray[1], loopArray[2] , .... ?
how to declare that?
Thanks
Adam

See this:

1 Like

Great!
Thank you.
and I have tested some thing like that, but only work when directly put them inside loop like:

 void loop() {
if (action == 0)
  doAction0 ();
else if (action == 1)
  doAction1 ();
else if (action == 2)
  doAction2 ();
else if (action == 3)
  doAction3 ();
else if (action == 4)
  doAction4 ();   }

doesn't work when do:


void loop()
{
void All_loops();
}
void All_loops()
{

if (action == 0)
  doAction0 ();
else if (action == 1)
  doAction1 ();
else if (action == 2)
  doAction2 ();
else if (action == 3)
  doAction3 ();
else if (action == 4)
  doAction4 ();

}

why? any reason there?

also, any difference between:

if (action == 0) 
  doAction0 ();

and:

if (action == 0)
{
  doAction0 ();
}

Although solved, here's something:

1 Like

Thank you xfpd!

Please post as small a program as you can where that All_loops() fails. I am very curious about why that is, and without seeing it I don't even believe it.

No. Well yes: in one you have braces that are not syntactically necessary.

But no difference in the generated code. If you only have a simple statement, you don't need the braces around it.

Some people will put them there anyway. Maybe they are forced to by the style police where they work. Maybe they claim it makes things clearer and unambiguous.

I don't answer to anyone but myself, and my habit is to use as little ink as possible, so no braces where none are needed.

Yes, this has caused some minor problem on a rare occasion. Fire me.

a7

1 Like

Hello shanren

Check, try and fine tune this small loop scheduler to your needs.

enum {LoopA, LoopB, LoopC};
int (*loops[])() {loopA,loopB,loopC}; 
/// loops ------
int loopA(void)
{
  Serial.println(__func__);
  delay(1000);
  return LoopB;
}
int loopB(void)
{
  Serial.println(__func__);
  delay(1000);
  return LoopC;
}
int loopC(void)
{
  Serial.println(__func__);
  delay(1000);
  return LoopA;
}
//----------
void setup(void)
{
  Serial.begin(115200);
}
void loop(void)
{
  static int call=LoopA;
  call = loops[call](); 
}

Have a nice day and enjoy coding in C++.

2 Likes

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