include::../summary.adoc[]

== 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:

1. `return`
2. `break`
3. `continue`
4. `goto`
5. `co_return`
6. `throw`

Examples of functions that never return the control flow to the caller:

1. `exit()`
2. `abort()`
3. `std::terminate()`
4. 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

[source,cpp,diff-id=1,diff-type=noncompliant]
----
int fun(int a) {
  int i = 10;
  return i + a;  // Noncompliant: There are following statements within the code block
  i++;           // Dead code
}
----

[source,cpp,diff-id=2,diff-type=noncompliant]
----
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

[source,cpp,diff-id=1,diff-type=compliant]
----
int fun(int a) {
  int i = 10;
  return i + a;
}
----

[source,cpp,diff-id=2,diff-type=compliant]
----
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 {cpp}:2008, 0-1-1 - A project shall not contain unreachable code
* MISRA C:2012, 2.1 - A project shall not contain unreachable code
* CWE - https://cwe.mitre.org/data/definitions/561[CWE-561 - Dead Code]
* https://wiki.sei.cmu.edu/confluence/x/5dUxBQ[CERT, MSC12-C.] - Detect and remove code that has no effect or is never executed

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

include::../highlighting.adoc[]

'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
