Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 997
Nathan Fellman Avatar asked Oct 09 '11 12:10

Nathan Fellman


2 Answers

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

like image 132
Vsevolod Dyomkin Avatar answered Oct 23 '22 05:10

Vsevolod Dyomkin


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.

like image 41
Greg Hewgill Avatar answered Oct 23 '22 06:10

Greg Hewgill