If Statement with Declaration

Nick Treleaven via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 4 10:08:54 PDT 2016


On Friday, 4 November 2016 at 13:56:57 UTC, Andrea Fontana wrote:
> If you don't like indentation you can simply ignore it or you 
> can use old goto :)
>
> {
>    int i = someFunc();
>    if (i < 0) goto outer;
>    // your code here
> }
> outer:

BTW there is a trick to avoid goto+label:

switch (true) {
default:
   int i = someFunc();
   if (i < 0) break;
   ...
}

If code after goto is long, the reader has to search for the 
label. With switch/break, the reader knows the current scope is 
just skipped, no need to interrupt reading of lines.

We could allow omitting the condition and default label:

switch {
   int i = someFunc();
   if (i < 0) break;
   ...
}

That would encourage the pattern to be used instead of the 
'triangle if' pattern - the rationale for breakable blocks:
https://issues.dlang.org/show_bug.cgi?id=8622


More information about the Digitalmars-d mailing list