Saturday, October 19, 2019

Generic loops for all scenarios

'for loops', 'while loops', and 'do while loops' are all specific cases of generic loops. Why not just have a generic loop structure that can be customized? while(true) loops can be used as generic loops.

-The crux of all loops is an implicit 'continue' statement at the end, and a way to escape.
-At any time you can branch to the top using 'continue'
-At any time you can branch out of the loop using 'break'

For readability:
-comment at the top of the loop what is going on with the loop, which should be done anyways.
-highlight branches so they stand out with a label left justified, like this (it would be nice if IDEs did something like this automatically)

while(true)
{
               stuff;
/*con*/   stuff; if(stuff){continue;}
               stuff;
/*brk*/   stuff; if(stuff){break;}
               stuff;
}

I find generic loops to be more readable than for-loops as you see exactly where an increment occurs and exactly where break check or a continue check occur.

Breaking out of outer loops

There should also be a way to continue and break in reference to an outer loop from within an inner loop, avoiding having to use a variable flag to pass this info between the 2 loops, or having to use a 'goto' statement which many want to avoid the like the plague. For example:

while(true)
{
       /*continue 2 goes here*/
       stuff;
       while(true)
       {
               stuff;
/*con2*/ if(stuff){continue 2;}
               stuff;
/*brk2*/  if(stuff){break 2;}
               stuff;
       }
       stuff;
}
/*break 2 goes here*/

Easy to replace For and Do While loops

//for loop equivalency
i=0;while(1)
{
        if (i>10) {break;}
        //do stuff
        i+=1;
}

//do while equivalency
while(1)
{
       //do stuff
       if (something is true) {break;}
}

//while equivalency (simply moves the check to the first line)
while(1)
{
       if(something is true){break;}
       //do stuff
}

//if equivalency
while(whatever)
{
    stuff;
    break;
}

No comments:

Post a Comment