switch-case statement without break

后端 未结 7 1695
鱼传尺愫
鱼传尺愫 2021-02-04 01:44

According to this book I am reading:

Q What happens if I omit a break in a switch-case statement?

A The break statement enables program execution to exit the swi

7条回答
  •  暖寄归人
    2021-02-04 01:53

    • If you don't include break in any of case then all the case below will be executed and until it sees break.

    • And if you don't include break in default then it will cause no effect as there are not any case below this 'Default' case.

    • And not using break generally considered as a bad practice but some time it may also come handy because of its fall-through nature.For example:

      case optionA:

      //optionA needs to do its own thing, and also B's thing.
      //Fall-through to optionB afterwards.
      //Its behaviour is a superset of B's.
      

      case optionB:

      // optionB needs to do its own thing
      // Its behaviour is a subset of A's.
      break;
      

      case optionC:

      // optionC is quite independent so it does its own thing.
      break;
      

提交回复
热议问题