我在 GCC 编译器版本 7.1.0 上测试 C++17 功能。这与fallthrough
属性有关,以下示例(现场示例)改编自此处的在线 CPP 参考
#include "iostream"
using namespace std;
int f(int n) {
switch (n) {
case 1:
case 2:
n = n + 20;
[[fallthrough]];
case 3: // no warning on fallthrough
n = n + 30;
case 4: // compiler may warn on fallthrough
[[fallthrough]]; // illformed, not before a case label
//n = n + 40; //commented out to test if compiler will warn.
}
return n;
}
int main()
{
cout << f(1) << endl;
cout << f(2) << endl;
cout << f(3) << endl;
cout << f(4) << endl;
return 0;
}
最后一个[[fallthrough]]
(for case 4:
) 格式不正确。
关于“根据标准处理格式错误的程序需要什么 C++ 编译器?”的问题 这里有最重要的答案,说明:
所以总结一下:如果一个格式错误的程序包含一个可诊断的违规行为,标准没有明确指定“不需要诊断”,那么符合要求的实现应该发出一个 diagnostic。
因此,我查看了标准 (N4713) 以查看它是否声明此问题不需要诊断。我找不到任何这样的声明。
有趣的是,在这一切之后,当我在最后一个之后添加以下语句时[[fallthrough]]
n = n + 40;
编译器警告(现场示例):
警告:属性“fallthrough”不在案例标签或默认标签之前
所以,这里有两个问题:
- 编译器是否错过了发出诊断,或者我在这里遗漏了什么?
- 如果是编译器问题,是否严重到需要报告?