不间断的switch-case语句 [英] switch-case statement without break

查看:84
本文介绍了不间断的switch-case语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这本书,我正在阅读:

According to this book I am reading:

Q如果我在switch-case语句中省略一个中断会怎样?

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

A break语句使程序执行可以退出switch构造.没有它,执行将继续评估以下case语句.

A The break statement enables program execution to exit the switch construct. Without it, execution continues evaluating the following case statements.

假设我有类似的代码

switch (option}{
    case 1:
    do A;
    case 2:
    do B;
    default:
    do C;
    break;
}

这是否意味着如果我选择情况1,A和C就完成了.如果我选择情况2,则B和C完成.如果我都不选择,则仅完成C.

Does this mean if I choose case 1, the A and C are done. If I choose case 2, B and C are done. If i choose neither, then only C is done.

如果是这样,如果在执行C之后省略中断,会发生什么情况.

if so, what happens if we omit the break after do C.

我认为这些都是不好的编程习惯,但是我很好奇如何深入了解它们的工作原理.谢谢

I assume these are bad programming practice, but I am curious what would happen to get a deeper understanding how it all works. Thanks

推荐答案

break 的作用类似于 goto 命令.或者,作为一个更好的示例,就像在 void 函数中使用 return 时一样.由于位于末尾,因此无论是否存在都没有区别.虽然,我喜欢包含它.

The break acts like a goto command. Or, as a better example, it is like when using return in a void function. Since it is at the end, it makes no difference whether it is there or not. Although, I do like to include it.

这篇关于不间断的switch-case语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆