...
Code Block | ||
---|---|---|
| ||
public int func(boolean condition) { int x = 0; if (condition) { x = foo(); /* Process x */ return x; } /* ... */ if (x != 0) { /* This code is never executed */ } return x; } |
The condition in the second if statement, (x != 0)
, will never evaluate to true
because the only path where x
can be assigned a nonzero value ends with a return
statement.
...
Remediation of dead code requires the programmer to determine not only why the code is never executed but also whether the code should have been executed, and then to resolve that situation appropriately. This compliant solution assumes that the dead code should have executed and consequently removes the return
from the body of the first conditional statement.
Code Block | ||
---|---|---|
| ||
public int func(intboolean condition) { int x = 0; if (condition) { x = foo(); /* Process x */ } /* ... */ if (x != 0) { /* This code is now executed */ } return 0; } |
Noncompliant Code Example (Dead Code)
...
Code Block | ||
---|---|---|
| ||
int p1 = foo(); int p2 = bar(); if (baz()) { return p1; } else { p2 = p1; } return p2; |
...