[ILUG-BOM] for and while loops

Philip S Tellis philip.tellis@[EMAIL-PROTECTED]
Thu Jan 17 11:33:03 IST 2002


On Wed, 16 Jan 2002, Abhir Joshi wrote:

>  In the source code of some packages, I have seen 'for (;;)' where
> 'while (1)' could have done the job.  Is it related to the
> efficiency of the code generated ?  I have also seen that the a java

There is no difference between a while loop and a for loop.  Both are 
entry controlled, both test for a condition.  The difference is for has 
an extra statement executed before the loop entry, and at the end of the 
loop.  If these two do not exist, the for and while are identical.  So:

while(condition)    ==    for(;condition;)

when they are compiled, both are converted to this algorithm in machine 
language:

initialise loop variable           (for only)
LOOP_START: check condition
   jnz LOOP_END
   do something
   change loop variable            (for only)
   goto LOOP_START
LOOP_END:

A do{}while loop is different though.  The condition is checked on exit:

LOOP_START:
   do something
   check condition
   jz LOOP_START

As you can see, after compiling, there is no for, no while, no 
do{}while.  Just if and goto.

To make your programs faster, replace all for, while, do loops with an 
if - goto construct.  <evil grin>

-- 
Be wary of strong drink.  It can make you shoot at tax collectors and miss.
		-- Lazarus Long, "Time Enough for Love"




More information about the Linuxers mailing list