无中断的 switch-case 语句 [英] switch-case statement without break

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

问题描述

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

According to this book I am reading:

Q 如果我在 switch-case 语句中省略了 break 会发生什么?

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.

如果是这样,如果我们在 do C 之后省略了 break 会发生什么.

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天全站免登陆