RFC: Behavior of continue in do/while loops.

Regan Heath regan at netmail.co.nz
Wed Sep 12 09:35:44 PDT 2007


Downs wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> I just came upon the interesting fact that using the "continue"
> statement in a do { } while() loop does not, in fact, continue with the
> next loop, but instead continues with the _condition_.
> I know this is the same behavior as in C, but as somebody who never
> encountered it before I can assure you, it's highly unintuitive.
> The confusion here stems largely from the way a do/while loop looks -
> the condition is found at the _end_ at the loop body, yet I expected
> continue to jump to the _beginning_.
> There is two questions I want to ask:
> First, if you were starting a new language, should the behavior of
> continue in that language match what I expected in this case?
> (theoretical case)
> And second, should the behavior be changed in the D programming
> language, even though it _might_ conceivably break code that relies on
> the current behavior? (practical case)
> 
> Looking forward to your comments,
>  --downs
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.7 (GNU/Linux)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
> 
> iD8DBQFG6AvvpEPJRr05fBERAnfQAJ0UapoxtHQCtIfTerkFe3iUnTHXtACfTFj4
> ennSYblhmnx1yOzb6izeCfs=
> =kBA4
> -----END PGP SIGNATURE-----

I tend not to use do/while in favour of while and for loops myself so I 
hadn't really bumped into this behaviour nor needed to imagine what it 
might do.

But, now that I know what it does, thinking about it, I reckon it's the 
correct (and intuitive - matter of opinion) thing for it to do and I 
don't think it should change.

I suspect whether it is intuitive or not depends on how you think of 
'continue', for example:

However,  if you think of 'continue' as meaning 'go to the next 
iteration' then you would expect it to do whatever it would have done at 
the end of this iteration, before the next one.

If you think of 'continue' as meaning 'go back to the start of 
the(this?) loop' then you wouldn't expect the condition to be evaluated.

I believe 'go to the next iteration' is the correct interpretation of 
'continue'.  In do/while, while and for to get from one iteration to the 
next you have to pass the condition.  This is the contract/guarantee 
that the loop provides.

Making the change you suggest will remove this guarantee, making it 
possible to go from iteration n to iteration n+1 without checking the 
condition.

Despite the fact that the first iteration of do/while should be safe 
without the guarantee the 2nd-nth ones might not be, eg.

if (*input != 0)
{
   char *p = input;
   do
   {
     ..etc..
     p++;
     ..etc..
     continue;
     ..etc..
   } while(*p != '\0');
}

Regan



More information about the Digitalmars-d mailing list