bug me now / bug me later

Robert Firth firth at sei.cmu.edu
Tue Jun 12 23:36:20 AEST 1990


In article <811 at sagpd1.UUCP> jharkins at sagpd1.UUCP (Jim Harkins) writes:

>Which is better:
>
>	a.	for(i = SIZE; i != 0; i -= STEP)
>or
>	b.	for(i = SIZE; i > 0; i -= STEP)
>
>Where this makes a difference is suppose SIZE is changed to 7.  Obviously
>'a' goes into an infinite loop, while 'b' stops.  In the real world SIZE and
>STEP could be variables that have been input by a user and manipulated a
>gazillion times before being used in the for loop.

First, the coding of the loop should have nothing to do with the values
of SIZE and STEP.  The code you write should be determined by the
postcondition you wish to establish.  If the required postcondition
is "i=0" then the correct continuation test is "i/=0"; on the other
hand if the required postcondition is "i<=0" then the test is "i>0".
This would all be much clearer in a language that allowed the condition
to be written positively, thus:

	loop
	  ...
	  exit when i=0
	end loop

	-- postcondition: i=0

Secondly, the question of errors.  If the loop variable reaches a state
from which the postcondition is unreachable, there is an error in the
code.  For example, if the postcondition is "i=0", the recurrence
relation "i'<i" (ie the new value of i will be strictly less than the
old value), and the current value of i is negative, then the postcondition
will never be reached.  If you suspect this can happen, you should test
for the situation, *but this test should be separate from the loop
termination test and not merged with it*.  The reason is that, if the
test fails, the last thing you want to do is terminate the loop silently
with the postcondition false.  You probably want to raise an exception,
enter a recovery block, or take some similar emergency action.

Hope that helps.



More information about the Comp.lang.c mailing list