Unreachable code: error or warning? [closed]
This is a language design question:
Do you think unreachable code (in programming languages in general) should raise a warning (i.e. "report problem and compile anyway") or an error ("refuse to compile")?
Personally I strongly feel it should be an error: if the programmer writes a piece of code, it should always be with the intention of actually running it in some scenario. But the C# compiler for example seems to disagree with this and merely reports a warning.
Note: I realize good dead code detection is a very difficult problem, but that is not the focus of this question.
Here are some examples of pieces of code where some statements are clearly unreachable:
return;
foo();
--
throw new Exception();
foo();
--
if (...) {
return;
} else {
throw new Exception();
}
foo();
An error means that the compiler is physically unable to deal with your code.
A warning means that the compiler is capable of dealing with your code, but it believe that what you have written is wrong in some way.
It seems pretty clear cut to me - it should be a warning.
Besides, what about the case where I've decided to shorten a method for debugging purposes:
public bool ShowMenu()
{
return true;
/* The standard implementation goes here */
}
I know its wrong, but for the compiler to ask me to also comment out that code would just be a pain.
It is very common to create dead code intentionally when debugging - a compiler that prevents this is unlikely to be popular with its users.
Generally speaking it should be an error.
One exception comes to my mind however:
if (false) {
doStuffThatITemporarilyDisabled();
}
Some developers might complain if your compiler denies compilation for code like that.
I think a warning is appropriate. Then the user can decide to use your OTHER switch that says "treat all warnings as errors" for when he does a Release build. Empowering the developer is always better than forcing your essentially random choices onto him.
I think it should be a warning.
Generally speaking, the common rule is that 'you should treat warnings as errors'. If I unintentionally write unreachable code, I will see it in the warnings, and fix it anyway.
However, sometimes, like Neil says, you intentionally create dead code, for debugging purposes or whatever reason. I'd really, really hate it if the compiler would not let me do that.