简体   繁体   English

Java - Switch语句和花括号

[英]Java - Switch statement and curly braces

I have a question associated with curly braces in switch-case block 我有一个与switch-case块中的花括号相关的问题

 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;  
}

AI know both codes should work the same way but I think there is some irrationalities here. AI知道这两个代码应该以相同的方式工作,但我认为这里存在一些不合理之处。 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. 由于断点应该导致从花括号块跳出,所以理论上第二个代码应该像这样顺利:1。断开跳出块2的路线。切换继续执行情况val2或默认导致在括号外没有任何break语句。

Which version you recommend to use and Are they really working the same way? 您建议使用哪个版本,它们是否真的以同样的方式工作?

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. 也许这是因为不经常使用块来分隔每个交换机分支的可见性。

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 并且除了if,while,switch,block之外,对流控制没有影响,除了它们是可选的情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM