6

unreachable code is compile time error in languages like Java. But why it is just warning in C++ & C? Consider following example:

#include <iostream>
int f()
{ 
    int a=3;
    return a;
    int b=6;       // oops it is unreachable code
    std::cout<<b;  // program control never goes here
}
int main()
{
    std::cout<<f()<<'\n';
}

Shouldn't compiler throw an error in this program, because statements after return statements in function f() will never get executed? What is the reason for allowing unreachable code?

bytecode77
  • 14,163
  • 30
  • 110
  • 141
Destructor
  • 14,123
  • 11
  • 61
  • 126
  • 3
    You would get a warning. – Sadique May 26 '15 at 11:26
  • 4
    Compiler isn't required to, but any decent compiler will warn you and you can force warnings to be errors if you want to. – eerorika May 26 '15 at 11:26
  • 4
    @TheodorosChatzigiannakis Debugging might be one reason. Just add a premature `return` while working on the code in the function or the code calling the function. – Some programmer dude May 26 '15 at 11:27
  • @user2079303: yes, -Werror can be used to force warnings to be errors but why compiler isn't required to generate error by default? – Destructor May 26 '15 at 11:28
  • 3
    @meet because the standard writers decided so. I wouldn't know why the decided so, but arguments for it would be 1) less rules for compiler = (potentially) simpler compiler 2) easier debugging as already mentioned. – eerorika May 26 '15 at 11:30
  • is a function that is not used technically also 'unreachable'? (At least for a standalone executable; but the *compiler* does not know what the *linker* is going to do next.) – Jongware May 26 '15 at 11:33

2 Answers2

17

Unreachable code is not a compile error in C++, but usually gives a warning, depending on your compiler and flags. If the compiler stopped when unreachable code is detected, then you would have less options for debugging code, because you would also have to manually remove code that is unnecessary.

A warning instead of an error makes sense. It's good that it's mentioned as one could have unintentionally left old code behind, but there is no reason not to compile anyway.

MuertoExcobito
  • 9,741
  • 2
  • 37
  • 78
bytecode77
  • 14,163
  • 30
  • 110
  • 141
5

Unreachable code is a warning because there is no need for it to be an error, further, it can't always be easily avoided.

  • Code expanded from macros or that check constants may result in unreachable code.
  • Code may reachable or not depending on the preprocessor defines (common cross platform developments, for example).
  • Generated code may result in unreachable code that isn't practical to detect in the generation phase.

Further, if you want this to be an error, GCC and Clang support -Wunreachable-code, so you can use -Werror=unreachable-code

ksyx
  • 41
  • 1
  • 9
ideasman42
  • 42,413
  • 44
  • 197
  • 320