Hello
I'm unsure which is the best design when using switch/case.
At the moment I do:
Should I do break outside the brackets?Code:switch (somecase) { default: case 1: { do_something(); break; } case 2: { print("blah"); break; } }
Hello
I'm unsure which is the best design when using switch/case.
At the moment I do:
Should I do break outside the brackets?Code:switch (somecase) { default: case 1: { do_something(); break; } case 2: { print("blah"); break; } }
I don't see why. I do it exactly this way, using the brackets as you do to create a seperates scope
I would put the break at the outside of the braces (brackets), yes.
I would also only use braces if I "need them", e.g. there's local variables in that case. Other cases don't actually need braces, so why use them [this is different to using braces on if/while statements, where a missing pair of braces will cause a bug. If you haven't got braces in a case-statement that needs them, the compiler will let you know that in no uncertain terms (or at least, it will give you an error of some sort).
It is of course a style issue on both accounts - someone else may well say differently, and any larger organization that does software engineering will have some sort of coding guidelines that are more or less strictly enforced. These may tell you how to do case-statements, as well as many other things.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Braces aren't required in case statements unless you actually need a separate scope.Should I do break outside the brackets?
Code:BTW, these are brackets: [ ] these are braces: { } and parenthesis: ( )
Thanks guys, you're very helpful!
It doesn't matter where you break, really. Whether you break within or without the braces it will break from the switch ... but that said I normally only use scoping with cases when I need to, unless it's a longun in which case I use it to show the scope clearly ... and I would break outside ... but does it matter? I don't think so. Though if you do decide to define a scope with the braces it is, IMO, 'nicer' to break outside of it, i.e. when the scope ends.