Once control flow has been moved out of the current code block, any subsequent statements become effectively unreachable.
Why is this an issue?
Some statements and expressions move the control flow out of the current code block. Additionally, some functions never return the control flow to
the caller. Any unlabeled statements that come after such a jump or function call is unreachable.
For instance, within a code block, code following a statement containing any of these keywords is effectively dead code:
-
return
-
break
-
continue
-
goto
-
co_return
-
throw
Examples of functions that never return the control flow to the caller:
-
exit()
-
abort()
-
std::terminate()
- Functions with the
[[noreturn]]
attribute.
How to fix it
The affected code block should be checked to verify the intended behavior, and the logic should be corrected, or the dead code removed.
Code examples
Noncompliant code example
int fun(int a) {
int i = 10;
return i + a; // Noncompliant: There are following statements within the code block
i++; // Dead code
}
int divide(int a, int b) {
if (b == 0) {
abort(); // Noncompliant: `abort()` never returns to the caller
std::cerr << "Divisor is 0!" << std::endl; // Dead code
}
return a / b;
}
Compliant solution
int fun(int a) {
int i = 10;
return i + a;
}
int divide(int a, int b) {
if (b == 0) {
std::cerr << "Divisor is 0!" << std::endl;
abort();
}
return a / b;
}
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, MSC12-C. - Detect and remove code that has no effect or is never executed