bug me now / bug me later

Art Boyne boyne at hplvli.HP.COM
Tue Jun 12 00:26:04 AEST 1990


jharkins at sagpd1.UUCP (Jim Harkins) writes:

>Lets say you have the following (you ADA people, please bear with me):
>
>	#define SIZE	6
>	#define STEP	2
>
>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.
>'a' goes into an infinite loop, while 'b' stops.

Personally, I always use (b) for the simple reason that it WILL stop.
However, if the SIZE really is supposed to be a multiple of step,
I would consider the following preferable:

  if (SIZE % STEP != 0)
	assert("SIZE not multiple of STEP in function ...");
  for (i = SIZE; i > 0; i -= STEP)
    ...

This checks the assumption of exact multiples, and issues a diagnostic
if the assumption fails.  Of course, if SIZE and STEP are entered by
the user, the test should be done at the time of data entry, with a
simple error at that time, not at time of use.

Art Boyne, boyne at hplvla.hp.com



More information about the Comp.lang.c mailing list