comp.lang.ada
 help / color / mirror / Atom feed
From: firth@sei.cmu.edu (Robert Firth)
Subject: Re: bug me now / bug me later
Date: 12 Jun 90 13:36:20 GMT	[thread overview]
Message-ID: <7498@fy.sei.cmu.edu> (raw)
In-Reply-To: 811@sagpd1.UUCP

In article <811@sagpd1.UUCP> jharkins@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.

  parent reply	other threads:[~1990-06-12 13:36 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
1990-06-07 23:26 bug me now / bug me later Jim Harkins
1990-06-08 16:51 ` Charles H. Sampson
1990-06-11 22:19 ` Wade Richards
1990-06-12 13:36 ` Robert Firth [this message]
1990-06-14  5:22   ` brnstnd
1990-06-14 15:00     ` David Kassover
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox