What is dead code?

Dead or unreachable code is code that will never be executed. It manifests itself as variables that are declared but never used, functions that are never called, or code that is skipped because of a branch. Since the dead code is not executed, it is an error, often a logic error. Dead code is created by cavalier programmers. An easy way to create dead code is by use of a goto statement and labels. Here is an example:

goto process_image;
j = j + 1;  // dead code here.

Since we have an unconditional branch to the label processing on the first line, the assignment statement on the second line can never be executed. A return statement can be used to make dead code. Here is an example:

int div_0(double a, double b)
{
    if (b == 0)
        return 1;
    else 
        return 0;
    return a/b;   // dead code here.
}

The arithmetic expression a/b is performed after two return statements inside an if-else. Since the if-else combination will result in one of the return statements being executed, the final return statement becomes an orphan, because it is impossible to get to. That is, since code execution is linear, and there is no conditional expression wrapping the return statement, any code after the return statements cannot possibly be executed.

Note that very few compilers will identify orphan code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s