Java switch cases: with or without braces?

前端 未结 8 1840
猫巷女王i
猫巷女王i 2020-12-23 11:05

Consider the following two snippets, with braces:

switch (var) {
  case FOO: {
    x = x + 1;
    break;
  }

  case BAR: {
    y = y + 1;
    break;
  }
}
<         


        
8条回答
  •  余生分开走
    2020-12-23 11:43

    You say the braces can be omitted because no variables names are being reused. By reusing variable names, I assume you mean declaring a new variable of the same type.

    The braces are actually most useful to ensure you don't end up reusing the same variable in different cases by mistake. They don't declare any variables today, but someone will add them tomorrow and without the braces the code is error-prone.

提交回复
热议问题