为什么即使我使用[[fallthrough]],GCC也会警告我一个漏洞?

s3r*_*vac 82 c++ switch-statement fall-through c++17

在下面的代码中,我使用[[fallthrough]]C++ 1z中的标准属性来记录需要的漏洞:

#include <iostream>

int main() {
    switch (0) {
        case 0:
            std::cout << "a\n";
            [[fallthrough]]
        case 1:
            std::cout << "b\n";
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用GCC 7.1,代码编译时没有错误.但是,编译器仍然警告我一个问题:

warning: this statement may fall through [-Wimplicit-fallthrough=]
    std::cout << "a\n";
    ~~~~~~~~~~^~~~~~~~
Run Code Online (Sandbox Code Playgroud)

为什么?

s3r*_*vac 104

您在属性后缺少分号:

case 0:
    std::cout << "a\n";
    [[fallthrough]];
    //             ^
case 1:
Run Code Online (Sandbox Code Playgroud)

[[fallthrough]]属性将应用于空语句(请参阅P0188R1).在这种情况下,当前的Clang主干提供了一个有用的错误:

error: fallthrough attribute is only allowed on empty statements
    [[fallthrough]]
      ^
note: did you forget ';'?
    [[fallthrough]]
                   ^
                   ;
Run Code Online (Sandbox Code Playgroud)

更新:Cody Gray 向GCC团队报告此问题.

  • @CodesInChaos`fallthrough属性仅允许在空语句`; 因为它后面没有空语句,所以gcc只是忽略它 (2认同)
  • @ musicman523那......似乎......错了?看起来,即使后面跟一个空语句,要求分号也会更加明智,只是拒绝编译. (2认同)
  • @CodesInChaos 如果没有分号,该属性将属于标签。 (2认同)