Given the following code:
bool doGoodThing;
switch (some_variable)
{
case 1:
case 2:
doGoodThing = true;
default:
doGoodThing = false;
}
Latest gcc version are smart enough to detect when variables are being assigned to but still not used, etcetera. Is there any compiler or flag that could trigger a warning saying that the whole switch does not make any sense for a code like this?
UPDATE: The question is not about doGoodThing variable. It is about a silly switch statement that doesn’t make much sense.
UPDATE 2: Passing “dupe” voters, before you mark it as a duplicate – read a question one more time. This is not about a warning for a missing “break” statement after “case”. This is about dead code, logical errors, static semantics analysis of the code by compiler. I do not need a warning if “break” is not there.
Okay, so we’re looking for a rule by which
would produce a warning, but
(which presumably is the intended code here) would not. One relatively simple way to go about this would be to always warn about fall-through except if a case is empty. I.e. don’t warn about the fall through from case 1 to case 2 because there’s no code in between, but warn about the fall through from 2 to default. However this approach would still warn about code that might be intentional.
A more sophisticated rule would be this: Produce a warning whenever there is an assignment to a variable
xsuch that there is no possible execution path, such that the assigned value would be used. I.e. in all possible execution paths that involvexbeing assigned the valuev,xwill either be reassigned to something else or go out of scope before any code that usesxis executed. This would warn about your code, but not the fixed example.Performing this analysis is definitely possible. However I’m not aware of any compiler that currently does such analysis (though all that really means is that gcc doesn’t).