Proposal: for/then/else statement

Timon Gehr timon.gehr at gmx.ch
Thu Jan 3 09:33:46 PST 2013


On Thursday, 3 January 2013 at 09:00:00 UTC, Linden Krouse wrote:
> ...
>
> Current solution:
>
> int[] nums = [1, 2, 3, 4, 5];
> int i = 6;
>
> bool intFound = false;
> foreach(n; nums)
> {
>     if(n == i)
>     {
>         intFound = true;
>         break;
>     }
> }
>
> if(!intFound)
> {
>     //i was not found, do stuff
> }
>
> Using for/then/else:
>
> int[] nums = [1, 2, 3, 4, 5];
> int i = 6;
>
> foreach(n; nums)
> {
>     if(n == i)
>         break;
> }
> then
> {
>     //i was not found, do stuff
> }
>
> Not only would this be more compact and easier to read, but it 
> should also be more efficient (less checking and less memory 
> usage).

Current solution:

foreach(n;nums) if(n==i) goto Lfound;
// i was not found, do stuff
Lfound:;

I think that any more or less decent compiler back end ought to 
be able to transform your boolean flag code into this form. (If 
the foreach loop is executed sufficiently many times, it does not 
make any kind of meaningful difference anyways.) This proposal is 
about convenient syntax.


More information about the Digitalmars-d mailing list