Why is this an issue?
Some statements (return
, break
, continue
, goto
, co_return
) and throw
expressions move control flow out of the current code block. Furthermore, some function do not return control flow (e.g. abort()
,
std::terminate()
, functions with the [[noreturn]]
attribute).
Any unlabeled statements that come after such a jump or function call are unreachable, and either this dead code should be removed, or the logic
should be corrected.
Noncompliant code example
int fun(int a) {
int i = 10;
return i + a; // Noncompliant
i++; // dead code
}
Compliant solution
int fun(int a) {
int i = 10;
return i + a;
}
Resources
- MISRA C:2004, 14.1 - There shall be no unreachable code
- MISRA C++:2008, 0-1-1 - A project shall not contain unreachable code
- MISRA C:2012, 2.1 - A project shall not contain unreachable code
- MITRE, CWE-561 - Dead Code
- CERT, MSC56-J. - Detect and remove superfluous code and values
- CERT, MSC12-C. - Detect and remove code that has no effect or is never executed