Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make MSVC warn or fail if a switch case falls through?

I would like to get a warning/error if one of my switch statements has a case which does not break. Is this possible?

switch (i){
case 1:
    cout << "one";
//forgot to break here, I want to be warned about this
case 2:
    cout << "two";
    break;
}

A similar Clang feature was discussed at going native 2012 conference but I need it for MSVC2013 http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Clang-Defending-C-from-Murphy-s-Million-Monkeys

Ideally I would want a warning for when two successive bodies are not separated by a break so that the example above would fail but this would not:

switch (i){
case 1:
    cout << "one";
    break;
case 2:
case 3:
    cout << "not one";
    break;
}
like image 659
odinthenerd Avatar asked Feb 20 '14 13:02

odinthenerd


People also ask

What is implicit Fallthrough?

Implicit fallthrough is when control flow transfers from one switch case directly into a following switch case without the use of the [[fallthrough]]; statement. This warning is raised when an implicit fallthrough is detected in a switch case containing at least one statement.

What is fall through in CPP?

It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line.


1 Answers

MSVC's CppCoreCheck added the warning C26819, which warns on an unannotated fallthrough. Here's how to enable CppCoreCheck if you haven't used it before.

I realize this is a seven year old post.

like image 199
Jordan Maples Avatar answered Oct 17 '22 13:10

Jordan Maples