Fixing the issue with "Statement unreachable"

matheus matheus at gmail.com
Thu Apr 30 18:25:48 UTC 2020


On Thursday, 30 April 2020 at 14:29:27 UTC, Steven Schveighoffer 
wrote:
> On 4/30/20 10:02 AM, matheus wrote:
>> ...
>> // 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).

Yes I got what you mean, and I would agree with that logic too, 
except that while this gives a warning:

bool test(){
     static if(cond){
         return true;
     }
     return false;
}

Just adding "else" to the code above will make it work normally:

bool test(){
     static if(cond){
         return true;
     }else
         return false;
}

This is a bit weird for me, I really thought the compiler would 
be smart enough to handle this.

If I was doing a benchmark between functions I'd like to do:

void func(){
     static if(TryDoSomethingA){
         doSomethingA();
         return;
     }
     doSomethingB();
}

But to make this work I'll need to add an extra "else", which I 
hate and I always try to avoid in my code.

Well my background is C and maybe there is a reason for the use 
of "else" with "static if".

> 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.

Exactly and I agree.

Matheus.


More information about the Digitalmars-d mailing list