首页 > 解决方案 > 为什么 gcc 会引发隐式失败警告?

问题描述

给定代码:

#include <stdlib.h> 

enum one {
    A, B
};

enum two {
    AA
};

int main(int argc, char *argv[])
{
    enum one one = atoi(argv[1]);
    enum two two = atoi(argv[2]);
    
    if ((one != A && one != B) || two != AA)
        return 1;
    
    switch (one) {
    case A:
        switch (two) {
        case AA:
            return 2;
        }
    case B:
        return 3;
    }
    return 0;
}

当我使用 using 编译它时,gcc -Wimplicit-fallthrough test_fallthrough.c我收到以下警告

test_fallthrough.c: In function 'main':
test_fallthrough.c:21:3: warning: this statement may fall through [-Wimplicit-fallthrough=]
   21 |   switch (two) {
      |   ^~~~~~
test_fallthrough.c:25:2: note: here
   25 |  case B:
      |  ^~~~

它试图警告什么,我能做些什么使它不发出警告(我宁愿避免添加诸如 之类的评论/* Falls through. */

标签: cgccgcc-warning

解决方案


break通常,编译器会在每个主体之后检查语句case,以确保程序流(失败)没有错误。

在您的情况下,case Abody 没有 a breakcase Bswitch语句与case A.

switch (one) {
    case A:
        switch (two) {
        case AA:
            return 2;
        }
         // <------ no break here, flow will continue, or fall-through to next case body
    case B:
        return 3;
    }
    return 0;
}

推荐阅读