Proposal: for/then/else statement

Tobias Pankrath tobias at pankrath.net
Thu Jan 3 01:41:36 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).

Python has a very similar thing, where you can have an else after 
a loop. However I always found it unintuitive whether the else 
branch gets executed if you break the loop or if you finish all 
iterations without breaking. Even now I'd have to look it up.


More information about the Digitalmars-d mailing list