Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'break' statement when using curly braces in switch-case

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;     } 
like image 238
griotspeak Avatar asked Sep 10 '11 20:09

griotspeak


People also ask

Can we use curly braces in switch case?

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.

How do you use a break statement in a switch case?

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.

Is break statement necessary in switch case?

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.

What is the purpose of {} squiggly braces in Java?

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.


2 Answers

Short answer: it doesn't matter.

like image 59
Oliver Charlesworth Avatar answered Oct 08 '22 03:10

Oliver Charlesworth


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.

like image 41
gregschlom Avatar answered Oct 08 '22 02:10

gregschlom