Why do we need break after case statements?

后端 未结 17 2233
猫巷女王i
猫巷女王i 2020-11-22 04:34

Why doesn\'t the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to e

17条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 05:05

    Not having an automatic break added by the compiler makes it possible to use a switch/case to test for conditions like 1 <= a <= 3 by removing the break statement from 1 and 2.

    switch(a) {
      case 1: //I'm between 1 and 3
      case 2: //I'm between 1 and 3
      case 3: //I'm between 1 and 3
              break;
    }
    

提交回复
热议问题