skipping a statemnet from inside a repeating block

John Colvin john.loughran.colvin at gmail.com
Sat Feb 16 09:39:54 PST 2013


On Saturday, 16 February 2013 at 17:03:30 UTC, Gopan wrote:
> On Thursday, 14 February 2013 at 16:57:17 UTC, Andrea Fontana 
> wrote:
>> Maybe you can write 2 different callbacks, one with if, one 
>> without and switch between them.
>
> I like that idea.  But it is less elegant.  For example, for a 
> timer callback, I may have to restart the timer with a new 
> callback function.  Instead of a single callback, if it is a 
> event subscription, other subscribers will be affected.
>
>> Maybe with a compile-time code generation to avoid code 
>> repetitions...
>
> I am looking for a more generic solution.  It should work with 
> within a loop also.  Just for the sake of achieving it I will 
> have to put those statements in a function, call it with 
> function pointer, etc.
>
> while(true)
> {
>    ...
>    Statement_1;
>    if(i == MY_MAGIC_NUMBER)
>    {
>       //done with this.
>    }
>    Statement_3;
>    ...
> }
>
>> Just for a int comparison or is it a different long operation?
> :)  you will ask me to short cut with a simple condition.
>
> Thanks,
> Gopan

for a loop:

while(true)
{
     Statement_1;
     if(magic)
     {
         //do something with magic
         Statement_2;
         break;
     }
     Statement_2;
}

while(true)
{
     Statement_1;
     Statement_2;
}

Simple (assuming that the break in the if statement is the only 
way out of the loop).

The code repetition can be easily removed by making Statement_1 
and Statement_2 mixins.

Remember that D is a compiled language, you can't change the 
instructions at runtime so there is no way to edit out the if 
statement at a runtime-dependant time. You have to specify a 
whole new code path to follow (i.e. the second while loop).


More information about the Digitalmars-d mailing list