c++ - 没有默认标签的 Switch-Case 中的无效值

标签 c++ switch-statement

我非常喜欢跳过 enum-switch-case 中的“default:”标签。因此,当枚举具有 switch-case 未处理的新值时,我会收到编译器警告。

现在一位同事说,当将一个整数传递给这个枚举未涵盖的 switch-case 时,我会遇到段错误。

至少我们使用的 gcc 可以正确处理它。还有 Visual Studio documentation说:如果“没有任何常量与 case 标签中的常量匹配,并且默认标签不存在 >>> 控制权转移到 switch 语句之后的语句。”

这是所有(或至少大多数)编译器的标准和行为吗?

最佳答案

MS 编译器似乎做对了。以下是标准 (6.4.2/5) 的内容:

If no case constant matches the condition, and if there is a default label, control passes to the statement labeled by the default label. If no case matches and if there is no default then none of the statements in the switch is executed.

关于c++ - 没有默认标签的 Switch-Case 中的无效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13561290/

相关文章:

c++ - 为什么这个 QT 应用程序以 SIGABRT 信号退出?

python - 寻找只能保存特定值的数据类型

c++ - Switch 语句 C++ 的问题

c++ - 使用 g++ 编译 SDL 的问题

c++ - nanoflann kdtree 适配器引发段错误

objective-c - 不同情况下相同 Action 的 Switch 语句语法

java: 一长串条件,怎么办?

go - 重写和缩短 switch case 表达式

c++ - 为什么此代码与运算符(operator)错误不匹配?

c++ - EnhTableWidget 字段的值更改(返回前)时发出信号