How can I tell gcc to warn (or fail) on switch/case statements without a break?

后端 未结 6 1335
有刺的猬
有刺的猬 2021-01-17 17:50

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 resu

相关标签:
6条回答
  • 2021-01-17 17:54

    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.

    0 讨论(0)
  • 2021-01-17 17:56

    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

    0 讨论(0)
  • 2021-01-17 17:56

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

    0 讨论(0)
  • 2021-01-17 18:03

    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

    0 讨论(0)
  • 2021-01-17 18:16

    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.

    0 讨论(0)
  • 2021-01-17 18:17

    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/

    0 讨论(0)
提交回复
热议问题