best infinite loop?

Hello dear Arduino community,

I riddle which kind of infinite loop is better? Are there any differences at all (because of the optimization)?

for( ; ; ) {
 // any code
}

... or ...

while( true ) {
 // any code
}

Many thanks in advance!

Are there any differences at all (because of the optimization)?

No. Because the body is empty the optimizer excises both of them equally.

Use the one that makes the most sense to you. The one that, a year from now, says "infinite loop" to you.

1 Like
#define EVER (;;);
...
for EVER

;D

:grinning:

This community rocks! 8)

#define ever (;;)

for ever {
  thank(CodingBadly && AWOL);
}
1 Like

void loop(){}

KenF:
void loop(){}

Yes, this is an infinite loop, but you can't do multiple ones, or can you? But thank you for the good will providing another answer to my question! :slight_smile:

Since I didn't mention it in my start posting: After connecting the Arduino into the PCs USB port, I want to run a specific main loop, which can be selected by a dip switch. Since there is no need to switch to another main loop at run time, I simply jump to the desired one when entering "loop()" for the first time. This way I can save some computation time, since I don't have to use "switch()" or "if()" on every cycle.

1 Like

Brduino:
Yes, this is an infinite loop, but you can't do multiple ones, or can you?

If any loop is infinite, there's no time for another :slight_smile:

byte breakout = 0;
void setup(){
// read dip swithches or something to determine which segment to run
}
void loop(){
switch(segment){ // jump to a segment & stay there
case 0:
while (breakout==0){
// infinite loop 0 
}
break;
case 1:
while (breakout==0){
// infinite loop 1
}
break;
:
:
case 99:
while (breakout==0){
// infinite loop 99
}
break;
} // end switch - but each while will never exit unless the code segment sets breakout = 1;
//                      could also change segment to jump to another section - becomes like a state machine
} // end loop
1 Like

Thanks CrossRoads! Your code nearly looks like mine, except that I saved the comparation "breakout==0", since the state doesn't need to be changed at runtime. (I'm currently hunting down a semicolon bug, so I didn't post the code, yet ...at least I guess it's a semicolon bug)

KenF:
If any loop is infinite, there's no time for another :slight_smile:

Only true if no break is present and they are not nested. :wink:
(well... of course only the most inner one is really looping...)

Aw, man, AWOL...you stole my thunder!! :wink:

Because the body is empty the optimizer excises both of them equally.

That is not correct. Sorry about the mistake.

The second sentence still stands.