Curly Braces in if() Statements, are They Always Necessary?

Flow control statements like if(), while(), or for() always only apply to the statement immediately behind them.

Example:

if( i > 10 )
    stopMotor();
waitForPushButton();

 

If is greater than 10, stopMotor() will be executed, else it won't.
waitForPushButton() will always be executed, because it is the second statement after the if().

The same is true for an if() with an else path:

if( i > 10 )
    stopMotor();

else

    startMotor();

waitForPushButton();

If you want multiple statements to be controlled by the if(), then you put curly braces around these statements:

 if( i > 10 ) {
    stopMotor();
    closeValve();
}
waitForPushButton();

 

So far, so good.

Why if()s Without Curly Braces are Dangerous


You can avoid nasty bugs in your code, if you use curly braces at all time, also if you only have a single statement after the if()
W
hy?

Example 1:

Let's suppose you want to test what happens, if the motor keeps running. Therefore, you will probably comment out (put comment characters in front of) the stopMotor() statement:

if( i > 10 )
    // stopMotor();
waitForPushButton();

But now waitForPushButton() is the next statement after the if(), and will only be executed, if i is greater than 10!
That's not what you have intended, and your sketch will behave totally different from you have expected.
Maybe you start thinking about why the motor functions in your code are interfering the pushbutton functions. Or you might even start searching for problems in your hardware!

Even worse: The missing indentation of the waitForPushButton() line lets you think that is not part of the if(), but line indentation has no meaning for the compiler, it is only meant for human eyes.

Example 2:

Let's assume you want the motor to be stopped and you also want the valve to be closed. Then you could easily make the mistake by just adding a new statement like this:

 if( i > 10 )
    stopMotor();
    closeValve();

The line indentation suggest that the code is correct, but, as said before, compilers don't care about indentation at all.
Since closeValve() is the second statement after the if(), it will always be executed, regardless of the value of i.

Last but not least, if()s, for()s, and while()s without curly braces bring problems when working with Visual Micro breakpoints.

Warning  Always put curly braces around statements after if()s, for()s, and while()s!

Unfortunately, even the example sketches from the Arduino web site follow this golden rule...