I use curly braces with all of my switch case statements in C/Objective-C/C++
I had not, until a few moments ago, considered whether including the break;
statement inside the braces was good or bad practice. I suspect that it doesn't matter, but I figure it is still worth asking.
switch (foo) { case 1: { // stuff break; } default: { break; } }
vs
switch (foo) { case 1: { // stuff } break; default: { // stuff } break; }
It's certainly not invalid to use braces in every case block, and it's not necessarily bad style either. If you have some case blocks with braces due to variable declarations, adding braces to the others can make the coding style more consistent.
You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
Short answer: it doesn't matter.
Just a give a slightly more detailed answer...
The official C99 specification says the following about the break statement:
A break statement terminates execution of the smallest enclosing switch or iteration statement.
So it really doesn't matter. As for me, I put the break inside the curly braces. Since you can also have breaks in other places inside your curly braces, it's more logical to also have the ending break inside the braces. Kind of like the return statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With