Correct use of curly brackets

I haven't found a description of the correct uses of the curly brackets {}. When should they be used and where should they appear in the sketch?

Red Haines

Use brackets to define what code is run for whiles, ifs, switch:case, and functions:

void setup() // a function
{
// stuff that runs once
} // end of setup

void loop() // another function
{ // stuff that will run over and over, such as:

if (digitalRead(pinX) == LOW)
{ 
do something if button is pressed
} // end of if

while (buttonCount <=12 )
{
// flash an LED to show count is still low, buttonCount perhaps incremented thru an interrupt
} // end of while
switch (stateMachine)
{
case 1:
// do stuff, then change to state 3
stateMachine = 3;
break;
case 2:
// do stuff, then change to state 1
break;
case 3:
// do stuff, then change to state 2
break;
} // end of switch

} // end of loop
1 Like

The curly brackets are at the start and end of any logical block. Blocks can have sub blocks and these also have their own {}. The trick is to have the start and finish brackets being equal in number and surrounding the correct sections of code.

To find the opening or closing bracket partner, put your cursor straight after the bracket and the IDE will highlight its partner. It may not necessarily be where you expect it and can help you work out why your program is not doing what you expected.

Weedpharma

As has been said, curly braces enclose logical block of code. One cause of confusion is that when used after an if/while etc, should there be only one command to be executed when the condition returns true then the curly braces can be omitted and the single command will be executed. Something like this

if (something == true)
    doThis();

Whilst this works I find it easier to read and understand if it is written as

if (something == true)
    {
      doThis();
    }

Notice the 2 changes. Braces have been used to positively identify the code to be executed, each brace has been put on its own line (a personal preference of mine) and the indentation of the code makes it easy to see what code will be executed if the condition is true.

I would strongly advocate the use of curly braces around such code even when they are not strictly necessary. It also makes it easy to add extra code at a later date by simply putting it in the braces, For instance

if (something == true)
    doThis();
    doThat();

is not the same as

if (something == true)
    {
      doThis();
      doThat();
    }

Many thanks for the three responses and examples!

Regards, Red