23

I thought those terms where synonymous, but a note in MISRA regarding dead code indicates this to be wrong? What's the difference? Is one a subset of the other?

Lord_Gestalter
  • 500
  • 1
  • 5
  • 14

4 Answers4

45

Dead code - code that is executed but redundant, either the results were never used or adds nothing to the rest of the program. Wastes CPU performance.

function(){
    // dead code since it's calculated but not saved or used anywhere
    a + b;
}

Unreachable code - code that will never be reached regardless of logic flow. Difference is it's not executed.

function(){
    return x;

    // unreachable since returned
    a = b + c;
}
domdomcodecode
  • 2,355
  • 4
  • 19
  • 27
  • So they are distinct and one is not the subset of the other? – Lord_Gestalter Apr 02 '14 at 06:30
  • @Lord_Gestalter Yes, they're distinct in definition. Both are redundant code, but the reason they're redundant is distinct. – domdomcodecode Apr 02 '14 at 09:06
  • So the empty statement ';' wouldn't be dead or unreachable code, since it's not executed but it could be reached (depending on the rest of the logic flow)? – jinawee Aug 16 '18 at 09:55
  • 1
    These definitions align with how I use the terms, but *dead code* is sometimes used as a synonym for *unreachable code*. Relevant Wikipedia articles: https://en.wikipedia.org/wiki/Unreachable_code , https://en.wikipedia.org/wiki/Dead_code – Max Barraclough Mar 01 '21 at 13:01
  • 1
    This answer seems to be positing a more clear-cut answer than the usage supports. See for example the rust dead_code warning, which emits on unused functions. (https://doc.rust-lang.org/rust-by-example/attribute/unused.html) – Sam Jul 31 '21 at 12:41
4

Dead Code

Code that performs functions that have no effect. Basically stuff that wouldn't make a difference if removed.

Unreachable Code

Code that due to other logic will never be executed. This is usually the sign of an error.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
3

Unreachable code

The code to which control flow never enters during the execution of the program. That is unreachable code is that code that is never executed during the course of execution of the program.

Dead code

The code that has no effect on the codes following it no matter how the control flow flows through the program. That is dead code is that code, that doesn't need to be executed during the course of execution of the program, or in other terms, is useless.

So, in true terms none of them is a subset of another. But both unreachable code and dead code are usually removed by the compiler during compilation process as a part of code optimization.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
1

unreachable code is something that would never be executed because there is no flow control to reach the code.

A dead code is something that gets (or might get) executed, but its results are never used.

Community
  • 1
  • 1
Linkon Ruhul
  • 105
  • 1
  • 6