Why unreachable code isn't an error in C++?
Asked Answered
C

2

7

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?

Ceceliacecil answered 26/5, 2015 at 11:24 Comment(6)
You would get a warning.Kings
Compiler isn't required to, but any decent compiler will warn you and you can force warnings to be errors if you want to.Extrude
@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.Roumell
@user2079303: yes, -Werror can be used to force warnings to be errors but why compiler isn't required to generate error by default?Ceceliacecil
@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.Extrude
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.)Revalue
A
18

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.

Ammo answered 26/5, 2015 at 11:28 Comment(0)
B
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

Beyrouth answered 14/9, 2017 at 4:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.