switch-case statement without break(无中断的 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 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无中断的 switch-case 语句


基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07