gpt4 book ai didi

c++ - GCC 编译器是否应该对这个涉及 [[fallthrough]] 属性的格式错误的 C++ 代码进行诊断?

转载 作者:IT老高 更新时间:2023-10-28 23:17:49 27 4
gpt4 key购买 nike

我在 GCC 编译器版本 7.1.0 上测试 C++17 功能。这与 fallthrough 属性有关,以下示例 (live example ) 改编自在线 CPP 引用 here

#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]]; // ill­formed, 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]](对于 case 4:)格式不正确。

关于“根据标准,对格式错误的程序需要什么 C++ 编译器?”的问题here有顶answer声明:

So to sum it up: if an ill-formed program contains a diagnosable violation for which the Standard does not explicitly specify "no diagnostic required", conforming implementations should emit a diagnostic.

因此,我查看了标准 (N4713) 以查看它是否声明此问题不需要诊断。我找不到任何这样的声明。

有趣的是,毕竟,当我在最后一个 [[fallthrough]]

之后添加以下语句时
n = n + 40;

编译器警告(live example):

warning: attribute 'fallthrough' not preceding a case label or default label

所以,这里有两个问题:

  1. 编译器是否错过了发出诊断信息,或者我是这里缺少什么?
  2. 如果是编译器问题,是否严重到需要报告?

最佳答案

  1. If it is a compiler issue, is it serious enough to be reported?

是的,一致性错误是重要的错误,开发人员依赖于符合标准的编译器(编译器可能具有不需要严格一致性的模式,尽管 gcc 需要 -pedantic to obtain all diagnostics required by the standard )错误获得的优先级是另一回事,但仅仅是记录错误并让编译器团队承认它是一个错误,这对 future 遇到错误的开发人员来说是一个巨大的帮助。

  1. Has the compiler missed out on emitting a diagnostic, or am I missing something here?

是的,根据 [dcl.attr.fallthrough#]p1,这是不正确的。 :

... The next statement that would be executed after a fallthrough statement shall be a labeled statement whose label is a case label or default label for the same switch statement. The program is ill-formed if there is no such statement.

并且编译器至少需要根据 [intro.compliance]p2.2 发出诊断信息:

If a program contains a violation of any diagnosable rule or an occurrence of a construct described in this document as “conditionally-supported” when the implementation does not support that construct, a conforming implementation shall issue at least one diagnostic message.

关于c++ - GCC 编译器是否应该对这个涉及 [[fallthrough]] 属性的格式错误的 C++ 代码进行诊断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51983560/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com