Unreachable code
Code cannot be reached during execution
Description
Unreachable code uses statement coverage to determine whether
a section of code can be reached during execution. Statement coverage checks whether a program
statement is executed. If a statement has test conditions, and at least one of them occurs,
the statement is executed and reachable. The test conditions that do not occur are not
considered dead code unless they have a corresponding code branch. If all the test conditions
do not occur, the statement is not executed and each test condition is an instance of
unreachable code. For example, in the switch
statements of this code,
case 3
never occurs:
void test1 (int a) { int tmp = 0; if ((a!=3)) { switch (a){ case 1: tmp++; break; default: tmp = 1; break; /* case 3 falls through to case 2, no dead code */ case 3: case 2: tmp = 100; break; } } } void test2 (int a) { int tmp = 0; if ((a!=3)) { switch (a){ case 1: tmp++; break; default: tmp = 1; break; // Dead code on case 3 case 3: break; case 2: tmp = 100; break; } } } |
In test1()
, case 3
falls through to
case 2
and the check shows no dead code. In test2()
,
the check shows dead code for case 3
because the break
statement on the next line is not executed.
Other examples of unreachable code include:
If a test condition always evaluates to false, the corresponding code branch cannot be reached. On the Source pane, the opening brace of the branch is gray.
If a test condition always evaluates to true, the condition is redundant. On the Source pane, the condition keyword, such as
if
, appears gray.The code follows a
break
orreturn
statement.
If an opening brace of a code block appears gray on the Source pane, to highlight the entire block, double-click the brace.
The check operates on code inside a function. The checks Function not called and Function not reachable determine if the function itself is not called or called from unreachable code.
Diagnosing This Check
Examples
Check Information
Group: Data flow |
Language: C | C++ |
Acronym: UNR |