Is it dangerous to use return; inside loop()?

Hi everyone, I'm writing a new piece of code and I'm trying to avoid using nested if() statements to help readability. For example, when creating functions, I avoid this:

void myFunction(int var){

  //if var is positive, execute myFunction()
  if(var > 0){
  
    //execute all of myFunction() inside if() statement, could lead to nested if statements!

  }

  return;

}

in favour of this:

void myFunction(int var){

  //if var is not positive, return, i.e. don't execute myFunction()
  if(var <= 0)
    return;
  
  //execute all of myFunction(), except this time we're not inside a big if() statement!

  return;

}

plus I've also been told by a friend who's a software developer/programmer that it's good practice to avoid nesting if() statements.

This is fine for functions, but for the Arduino loop statement, I was wondering if I could do the same. I'm aware that the main.c file has defined the main() function in Arduino as:

int main(void)
{
	init();

	initVariant();

#if defined(USBCON)
	USBDevice.attach();
#endif
	
	setup();
    
	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
        
	return 0;
}

so I know that if I return from loop(); then it will just execute again as it is inside an endless for(;;) loop. so, for example, when I run this code:

bool someVariable = false;

void setup(){
  Serial.begin(115200);
  Serial.flush();
}

void loop(){
  
  delay(1000);
  Serial.println(F("Hello!"));

  if(!someVariable)
    return;

  Serial.println(F("Hi!"));

}

the only message I see in the Serial monitor is "Hello", and the Serial.println(F("Hi!")); will never execute due to the if() statement.

So, my questions are, am I correct in how I have described the way the final code will run? and if so, is it bad practice or potentially dangerous to rely on return; inside loop()?

If you want to quit any function immediately and return to where it was called then you use return;

loop() is just a function called from main() and as such it is legitimate to return; from it and have it called again from the start

2 Likes

of course not


void loop ()
{
    if (! Serial.available ())
        return;

    ...
}
1 Like

As a fun bonus, if someVariable is static or const the compiler will eliminate the if and the second println because it's dead code.

1 Like

ah cool! that's cool that the compiler actually figures out how a code will run, I thought it just eliminated functions and variables that were never used

But only to a limited extent. It can not grasp semantics, only look for definite patterns that have easily predictable outcomes. Here there is no magic, though - surely if it can eliminate a function, it can eliminate a code block.

A logical test of a constant value, is a pretty easy thing to detect, if you see what I mean...