Java switch cases: with or without braces?

前端 未结 8 1780
猫巷女王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.

    0 讨论(0)
  • 2020-12-23 11:44

    With braces.

    There are so many things that can go wrong with switch statements I try to avoid them where I can, i.e.

    1. Forgetting breaks and thus having case fall-throughs
    2. Forgetting a default case and thus not catching an un-catered for condition
    3. Accidentally reusing variables between case statements, or worse yet, affecting a variable which IS sharing a variable between case statements.

    Using braces is one way to prevent both intentional and accidental sharing of variables between case statements

    0 讨论(0)
提交回复
热议问题