10

I have a complicated switch statement, and I forgot to put a break at the end of one of the cases. This is quite legal, and as a result I had a fall-through to the next case.

Is there any way to have gcc warn (or even better, fail) if I neglect to put a break statement?

I realize that there are many valid use cases (and I use them often in my code), as exemplified in this question, so obviously such a warning (or failure) would need a simple waiver so that I could easily say, "I do want to fall-through here."

Is there any way to tell gcc to do this?

Community
  • 1
  • 1
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319

6 Answers6

6

There's a discussion about such a feature (-Wswitch-break) at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=7652. But it doesn't seem to be implemented yet

Vsevolod Dyomkin
  • 9,343
  • 2
  • 31
  • 36
4

This check is available in Cppcheck, a free static analyser for C and C++ code. The check is currently marked "experimental", so you will need to use the --experimental command line switch to turn it on.

This check warns against a nonempty case clause that falls through to the next case without a control flow statement such as break, continue, return, etc, unless there is a comment with wording such as // fall through immediately preceding the next case.

You can get an idea for the kinds of constructs this handles by having a look at the switchFallThroughCase test cases in the source code.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 1
    I can no longer find this kind of check in cppcheck-1.83 and am not able to enable it with --experimental – Andy May 09 '18 at 07:33
3

GCC 7 has a warning enabled with -Wextra or -Wimplicit-fallthrough(=[1-5])?: https://developers.redhat.com/blog/2017/03/10/wimplicit-fallthrough-in-gcc-7/

Dan Berindei
  • 7,054
  • 3
  • 41
  • 48
2

I just went through gcc options, and there is none that will at least give you a notice. There are -Wswitch, -Wswitch-default and -Wswitch-enum ( http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options ), but none of them will work for you.

my best bet would be to use 'else if' statements

fazo
  • 1,807
  • 12
  • 15
1

You could construct a regexp for grep/perl/emacs/etc to find all places where there's no break before case.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
0

Short answer is no, there is no such flag in gcc to do that. Switch case is used for the fall through more often so that is why it does not make sense to have such a flag in gcc.

Harman
  • 1,571
  • 1
  • 19
  • 31
  • 2
    I think it makes sense, it just doesn't need to default to on. Seems like it may be appropriate for -Wextra or -pedantic. – Jason Dagit Oct 28 '11 at 01:13