5

I have a question associated with curly braces in switch-case block

 switch( conditon ) { 

   case val1: {
      // something 
   }
   break;
   case val2: {
      // something 
   }
   break; 
   default:
   break;  
}

or something like this:

 switch( conditon ) { 

   case val1: {
      // something 
      break;
   }
   case val2: {
      // something 
      break;
   } 
   default:
   break;  
}

A I know both codes should work the same way but I think there is some irrationalities here. As the break should cause jumping out from curly braces block so theoretically second code should do smoothen like this: 1. break course jumping out of block 2. switch continues execution case val2 or default cause outside the braces there isn't any break statement.

Which version you recommend to use and Are they really working the same way?

Michał Ziobro
  • 7,390
  • 6
  • 50
  • 99
  • 2
    You can put a block almost anywhere, inside a case is no exception, but it has no influence on control flow – amit Mar 26 '15 at 09:44
  • 1
    A break inside a mere compound statement (and no switch or loop) is not permitted. Thus, it does not "jump out of a block". – laune Mar 26 '15 at 09:47
  • Scopes define the lifetime and visibility of the contained variables, that's all. – Binkan Salaryman Mar 26 '15 at 09:48
  • You can also leave the curly braces out for each of the `case` blocks - they are maybe useful for delimiting the scope of variables, but they are not *required*. – Jesper Mar 26 '15 at 10:20
  • I know but i have variables with the same name and using different names will be misleading cause this is reading of ids from URI in android content provider – Michał Ziobro Mar 26 '15 at 11:47

2 Answers2

5

Try this:

{
System.out.println("A");
break;
System.out.println("B");
}

You'll see

$ javac Y.java 
Y.java:35: error: break outside switch or loop
    break;
    ^
1 error

This means: you can't use it in a block, it has no effect in combination with a block.

I would not put the break outside the block, but I've never seen coding rules demanding either way (and you could put up arguments for both sides). Maybe this is because blocks aren't used very frequently to separate visibility per switch branches.

laune
  • 30,276
  • 3
  • 26
  • 40
  • I understand so reasonably better approach will be in this situation placing break inside curly places I think if they are associated with switch not the blocks itself. Like switch { case A: block case B block default block } – Michał Ziobro Mar 26 '15 at 10:11
  • Use what *you* feel provides better readability. - Check after three months ;-) – laune Mar 26 '15 at 10:14
2

Curly braces limit the scope of variables. And have no effect on flow control other than if, for, while, switch.. blocks, except for the cases where they're optional

yiabiten
  • 782
  • 8
  • 25