Musings on infinite loops and not reachable returns

anonymous anonymous at example.com
Tue Mar 25 14:17:25 PDT 2014


On Tuesday, 25 March 2014 at 20:49:57 UTC, bearophile wrote:
> This code compiles with no errors or warnings:
>
>
> struct Foo {
>     int opApply(int delegate(ref ubyte) dg) {
>         int result;
>         ubyte x;
>         while (true) {
>             result = dg(x);
>             if (result) return result;
>             x++;
>         }
>         //return result; // Warning: statement is not reachable
>     }
> }
>
> struct Bar {
>     int opApply(int delegate(ref ubyte) dg) {
>         int result;
>         foreach (y; Foo()) {
>             result = dg(y);
>             if (result) return result;
>         }
>         return result; // required
>     }
> }
>
> void main() {}
>
>
>
> Note how the opApply() of Foo should not end with a return, 
> while the opApply() of Bar is required by the D compiler to end 
> with a return.
>
> Yet, Foo is contains an infinite loop, so the result of Bar 
> will not be reached. But the type system of D is not strong 
> enough to see that.

(It's not an infinite loop, but the return is dead code.)

When you know that it won't be reached, you can (should?) put
assert(false) instead of a return.


More information about the Digitalmars-d-learn mailing list