Search code examples
cgccgcc-warning

Why does gcc throw an implicit-fallthrough warning?


Given the code:

#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;
}

When I compile it using using gcc -Wimplicit-fallthrough test_fallthrough.c I get the following warning

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:
      |  ^~~~

What is it trying to warn against and what can I do so that it does not warn (I would prefer to avoid adding comments such as /* Falls through. */)


Solution

  • You're missing a break in the first switch statement, it may fallthrough to the sencond case, it can execute case A and afterwards Case B, hence the warning.

    //...
    switch (one)
    {
    case A:
        switch (two)
        {
        case AA:
            return 2;
        }
        break; //breaking case A removes the warning.
    case B:
        return 3;
    }
    //...
    

    Side note:

    • Using argc to check if argv[1] and argv[2] are present is always a good idea.