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()
?