Fixing the issue with "Statement unreachable"

Steven Schveighoffer schveiguy at gmail.com
Thu Apr 30 14:29:27 UTC 2020


On 4/30/20 10:02 AM, matheus wrote:
> On Thursday, 30 April 2020 at 09:10:16 UTC, Timon Gehr wrote:
>> On 30.04.20 08:00, Walter Bright wrote:
>>> Evidently, your example must be different from this. Please post a 
>>> complete example.
>>
>> You need -W. -W also notices the dangling elses, the intended code is 
>> this:
> 
> True and by the way I minimized the code:
> 
> // THIS WORKS - https://d.godbolt.org/z/3v-gW2:
> import std.stdio;
> bool test(){
>      static if(cond){
>          if(func()){return true;}
>      }
>      return false;
> }
> 
> enum bool cond = true;
> bool func();
> 
> void main(string[ ] args) {
>      writeln(test());
> }
> 
> 
> // WHILE BELOW GIVES THE ERROR: https://d.godbolt.org/z/8rNdjJ
> import std.stdio;
> bool test(){
>      static if(cond){
>          return true;
>      }
>      return false;
> }
> 
> enum bool cond = true;
> bool func();
> 
> void main(string[ ] args) {
>      writeln(test());
> }
> 
> As you can see, when you explicitly define a return inside a static if, 
> the compiler emits the warning.

Right, the first would still include the return false as generated code, 
this is not in dispute. And in fact, in your case, I would say the error 
is legitimate (that line is not reachable).

But in the case of a template where the condition is passed in, the line 
is reachable if the condition is one way.

However, there are other reasons why this might be "reachable" in other 
cases. For example, you could have:

version(abc)
    enum cond = false;
else
    enum cond = true;

which means that if you *compile* it a certain way, then it's reachable.

> I think this is a wrong behavior and the warning only should be emitted 
> if the code above had an "else", like for example:
> 
> // https://d.godbolt.org/z/fgY34m
> import std.stdio;
> 
> bool test(){
>      static if(cond){
>          return true;
>      }else{
>          return false;
>      }
>      return false;
> }
> 
> enum bool cond = true;
> bool func();
> 
> void main(string[ ] args) {
>      writeln(test());
> }
> 
> In the above the warning makes sense.

This makes a lot of sense, and probably is the way to go

-Steve


More information about the Digitalmars-d mailing list