Consider the following two snippets, with braces:
switch (var) { case FOO: { x = x + 1; break; } case BAR: { y = y + 1; break; } }
Without braces:
switch (var) { case FOO: x = x + 1; break; case BAR: y = y + 1; break; }
I know that, in the snippet with braces, a new scope is created by enclosing each case in braces. However, if each case does not need the new scope (i.e. no variable names are being reused), is there any sort of performance penalty for using the braces with a case?
The braces are always needed following the switch statement. No braces are needed following any case. If the variable is equal to one of the values following a case, then the code following the case is executed.
Bookmark this question. Show activity on this post. In a C switch-case flow control, it's required to put curly braces { } after a case if variables are being defined in that block.
Braces { } not required for one statement (but are always good) If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.
The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases.
is there any sort of performance penalty for using the braces with a case?
None.
The curly braces are there to help the compiler figure out the scope of a variable, condition, function declaration, etc. It doesn't affect the runtime performance once the code is compiled into an executable.
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