Proposal: for/then/else statement

Linden Krouse ztaticnull at gmai.com
Thu Jan 3 00:59:59 PST 2013


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).


More information about the Digitalmars-d mailing list