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

Should there be a diagnostic from GCC compiler for this ill-formed C++ code involving [[fallthrough]] attribute?

我在 GCC 编译器版本 7.1.0 上测试 C++17 功能。 这与 fallthrough 属性和下面的示例 (live example) is adapted from online CPP reference 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:)格式错误。

关于 "What is the C++ compiler required to do with ill-formed programs according to the Standard?" here has the top 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)错误获得的优先级是不同的故事,但仅仅记录错误并让编译器团队将其确认为错误可能对 运行 进入错误的未来开发人员有很大帮助。

  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.

在我发布这个问题后的某个时间,有人根据这个问题报告了 bug
我等着看它是否会被接受。它已被 接受并分配 ,并且基于错误报告中的 comment 将生成补丁 。所以这有效地回答了我的两个问题。

但是,我会接受@ShafikYaghmour 给出的答案,因为它包含解决我问题的要点。