问题
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?
回答1:
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]];
.
回答2:
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
回答3:
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++;
来源:https://stackoverflow.com/questions/8809154/how-to-make-gcc-clang-warn-about-missing-breaks-in-switch-statements