Fixing spurious "statement is not reachable" in template code

tsbockman via Digitalmars-d digitalmars-d at puremagic.com
Tue Oct 27 01:42:33 PDT 2015


On Tuesday, 27 October 2015 at 07:50:37 UTC, Daniel Murphy wrote:
> Easy to fix:
>
> void reachIf(bool x)()
> {
>      static if(!x)
>          return;
>      else
>          writeln("reached");
> }
>
> The warning is correct, and incredibly annoying.

Yes, it is easy to work around the problem in my simple example 
code. Real world examples are not generally so simple, though - 
often, an equivalent fix would require a `static foreach(...) { 
... } else` construct to avoid adding a redundant (and possibly 
quite complex) predicate.

No, the warning is not correct.

When a "statement is not reachable" warning is generated during 
analysis of a regular function, it means that that statement can 
*never* execute, no matter what parameters are fed in.

This is a very useful warning, because why would the programmer 
deliberately write dead code? Clearly something is wrong (whether 
in the code being compiled, or the compiler itself).

On the other hand, when a "statement is not reachable" warning is 
generated based on a specific combination of compile-time 
parameters, there is likely nothing wrong with the code.

The purpose of templates is code reuse. Forcing the programmer to 
manually prune each possible instantiation by sprinkling `static 
if`s with redundant predicates everywhere hinders this goal.


More information about the Digitalmars-d mailing list