Is there any compiler or option to trigger a warning for an operator without considering errors and errors?

Given the following code:

bool doGoodThing; switch (some_variable) { case 1: case 2: doGoodThing = true; default: doGoodThing = false; } 

The latest version of gcc is smart enough to detect when variables are assigned but still not in use, etc. Is there any compiler or flag that might trigger a warning that the entire switch makes no sense for such code?

UPDATE . The question is not the doGoodThing variable. It's about the silly wording of switch that doesn't make much sense.

UPDATE 2 : Skip the "tricksters" before you mark it as a duplicate - read the question again. This is not about warning a missing break statement after a case. This is about dead code, logical errors, static semantic analysis of code by the compiler. I do not need a warning if "break" does not exist.

+4
source share
2 answers

Ok, so we are looking for a rule by which

 bool doGoodThing; switch (some_variable) { case 1: case 2: doGoodThing = true; default: doGoodThing = false; } 

will give a warning but

 bool doGoodThing; switch (some_variable) { case 1: case 2: doGoodThing = true; break; default: doGoodThing = false; } 

(which is supposedly the intended code here) will not. One relatively simple way to do this is to always warn of failure, unless the case is empty. That is, do not warn about failure from case 1 to case 2, because there is no code between them, but warn about failure from 2 to the default value. However, this approach still warns of code that may be intentional.

A more complicated rule would be to issue a warning when there is an assignment to the variable x , so that there is no possible execution path to use the assigned value. That is, in all possible execution paths in which x is assigned the value v , x will either be reassigned to something else, or go out of scope before any code that uses x is executed. This will warn about your code, but not a fixed example.

Performing this analysis is certainly possible. However, I do not know of a single compiler that currently does such an analysis (although all this really means that gcc is not working).

+4
source

If you are talking about a missing gap in the switch statement, this is requested by eGancement in GCC .

EDIT 2: if you used Java, FindBugs could do it for you

EDIT again: CPPCheck seems to detect something related :

redundant assignment in switch statement

+5
source

Source: https://habr.com/ru/post/1386725/


All Articles