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 语句
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
