Proposal: for/then/else statement

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Thu Jan 3 09:58:37 PST 2013


On Thu, 03 Jan 2013 09:59:59 +0100
"Linden Krouse" <ztaticnull at gmai.com> wrote:

> My proposal is for a slight addition to for and foreach 
> statements by allowing different blocks of code to be executed 
> whether the loop is exited from the condition failing or a break 
> statement. These would of course be independently optional.
> For example:
> 
> for(int num = 0; num < 10; num++)
> {
>      if(<condition>)
>          break;
> }
> then
> {
>      //num successfully counted up to 10
>      //do stuff...
> }
> else
> {
>      //loop was broken prematurely
>      //do other stuff...
> }
> 
> One instance where this would be useful is in situations when 
> code should be executed if an item is not found while searching.
> For example:
> 
> 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).

Yea, I've occasionally found myself wishing we had those.



More information about the Digitalmars-d mailing list