Loop until condition is true

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Sat Jun 18 19:39:16 EDT 2005


In article <nha8b11f7c0ca8t2r7acopqb9uqm3gbqlm at 4ax.com>,
 Andrea Griffini <agriff at tin.it> wrote:

> On Sat, 18 Jun 2005 13:35:16 -0000, Grant Edwards <grante at visi.com>
> wrote:
> 
> >AFAICT, the main use for do/while in C is when you want to
> >define a block of code with local variables as a macro:
> 
> When my job was squeezing most out of the CPU (videogame
> industry) I remember that the asm code generated by
> 
>    while (sz-- > 0)
>    {
>      /* do some stuff */
>    }
> 
> was indeed worse than
> 
>    do
>    {
>      /* do some stuff */
>    } while (--sz);
> 
> because of the initial "empty-loop" test (conditional jumps
> were bad, and forward conditional jumps were worse).
> So where at least one iteration was guaranteed the do-while
> loop was a better choice.

Hmm.  I don't know what compiler you were using, but in my experience 
it's fairly typical to compile while(<test> ...) { <body> ... } as

      j test
body: <body>
      ...
test: <test>
      ...
      je body  ;; or whatever your condition is

To turn this into a do { <body> ... } while(<test> ...), you need only 
remove the initial "j test" instruction.  Even if forward conditional 
jumps are bad for your particular architecture, this method avoids the 
problem neatly.

Personally, I'd be pretty suspicious of the quality of a compiler that 
produced radically different code for these two constructs without some 
damned good reason.

-M

-- 
Michael J. Fromberger             | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA



More information about the Python-list mailing list