Why do we need break after case statements?

后端 未结 17 2063
猫巷女王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 04:48

    Historically, it's because the case was essentially defining a label, also known as the target point of a goto call. The switch statement and its associated cases really just represent a multiway branch with multiple potential entry points into a stream of code.

    All that said, it has been noted a nearly infinite number of times that break is almost always the default behavior that you'd rather have at the end of every case.

提交回复
热议问题