Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make gcc/clang warn about missing breaks in switch statements

Is there any way to make gcc or clang warn about missing breaks in switch statements?

Specifically, I almost always want case statements to end with breaks, and it would be great it I could get the compiler to complain if I don't. Even better would be if it would look for either a break statement or a "// fall through" comment.

Is there a different solution people use to help themselves not screw this up?

like image 558
sligocki Avatar asked Jan 10 '12 19:01

sligocki


3 Answers

With Clang trunk, use -Wimplicit-fallthrough. If you're using C++11, intentional fallthrough can be marked with a [[clang::fallthrough]]; statement (see the documentation for this attribute for more information). The warning does not (yet) check for 'fall through' comments. This feature won't be in the upcoming 3.1 release of Clang, but it will (probably!) be in 3.2.

Edit: Clang's attribute is now part of C++17, under the name [[fallthrough]];.

like image 83
Richard Smith Avatar answered Nov 01 '22 18:11

Richard Smith


As far as I can see, that's still an un-assigned feature request in gcc.

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=7652

like image 43
Joachim Isaksson Avatar answered Nov 01 '22 18:11

Joachim Isaksson


You asked that it would be great if it will look for either a break statement or a "// fall through" comment.

Remember Henry Spencer's first of the Ten Commandments for C programmers?

1. Thou shalt run lint frequently

It looks like what you need is PC-Lint / flexelint. Here is warning 616:

616 control flows into case/default -- It is possible for flow of control to fall into a case statement or a default statement from above. Was this deliberate or did the programmer forget to insert a break statement? If this was deliberate then place a comment immediately before the statement that was flagged as in:

case 'a': a = 0;
   /* fall through */
case 'b': a++;
like image 2
ouah Avatar answered Nov 01 '22 16:11

ouah