Why do we need break after case statements?

后端 未结 17 2033
猫巷女王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:51

    Why doesn't the compiler automatically put break statements after each code block in the switch?

    Leaving aside the good desire to be able to use the identical block for several cases (which could be special-cased)...

    Is it for historical reasons? When would you want multiple code blocks to execute?

    It's mainly for compatibility with C, and is arguably an ancient hack from the days of old when goto keywords roamed the earth. It does enable some amazing things, of course, such as Duff's Device, but whether that's a point in its favor or against is… argumentative at best.

提交回复
热议问题