where to put break in switch/case statement with blocks
I usually put the break
inside the braces, like this:
switch (foo) {
case bar: {
int x = 5;
printf("%d\n", x);
break;
}
case baz: {
// ...
break;
}
}
However, since it's my rule I'm free to break it (no pun intended) whenever I want.
It's a matter of style.
I would put break
outside the closing brace just to make it more readable.
It should appear after.
For example:
switch(value)
{
case 0:
{
// this ...
// that ...
// and the other ...
}
break;
}
Edited text below
This mostly to improve readability and maintainability here's an example.
switch (value)
{
case 0:
// Do this...
// Do that...
break;
case 1:
//and the other...
break;
}
and
switch (value)
{
case 0:
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
break;
case 1:
//and the other...
break;
}
Now compare with
switch (value)
{
case 0:
{
// Do this...
// Do that...
}
break;
case 1:
//and the other...
break;
}
and
switch (value)
{
case 0:
{
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
break;
}
case 1:
{
//and the other...
}
break;
}
When you start to come across cases of nested switch statements it can get very confusing indeed.
Just a pointer.
Now some of you are still wondering what I am getting at. Here it is. A piece of legacy code stopped working and noone could work out why. It all boiled down to a piece of code structured like the following:
switch (value)
{
case 0:
{
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
break;
}
case 1:
{
//and the other...
}
break;
}
It took a long time to pin down this code, but on checking the change logs it was originally as followws:
switch (value)
{
case 0:
{
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
// *** A line of code was here ***
break;
}
case 1:
{
//and the other...
}
break;
}
Admittedly the original code wasn't consistant with itself, but by having the break within the curly brackets the code compiled when the one line of code was deleted by accident. If the break had been outside of the brackets then it wouldn't have.
You put it wherever you like. Make sure you stay consistent throughout the entire project. (Personally, I put it outside.)