Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!zephyr.ens.tek.com!tektronix!nosun!qiclab!m2xenix!puddle!p15.f42.n105.z1.fidonet.org!Jim.Long From: Jim.Long@p15.f42.n105.z1.fidonet.org (Jim Long) Newsgroups: comp.lang.modula2 Subject: Why are the loops so awkward? Message-ID: <5673.2676D525@puddle.fidonet.org> Date: 13 Jun 90 19:04:04 GMT Sender: ufgate@puddle.fidonet.org (newsout1.26) Organization: FidoNet node 1:105/42.15 - Bink of an Aye, Portland OR Lines: 45 In a message of <12 Jun 90 14:17:02>, Peter M. Perchansky (1:273/101) writes: > Why not do the following: > > PROCEDURE P (VAR s: ARRAY OF CHAR); > VAR > i, len : CARDINAL; > BEGIN > len := Length (s); > FOR i := 0 TO len DO > Process (s[i]) > END; > END P; > > 1) I am not sure why you subtracted one from the length in your >example since Length should return the given values given the following >examples: > > s := ''; (* empty string *) > (* len will equal 0 *) And Process will process s[0], even though s[0] is indeterminate. > 2) If you must subtract one, it is better to use the following: > len := Length (s) - 1; instead of subtracting 1 from len > in the FOR loop It depends on what 'better' means. Some approaches take the time to save some memory space, some approaches take the space to save time. A WHILE will avoid the need for a decrement and solve the zero length problem at once: i := 0; WHILE i < Length( s ) DO Process( s[ i ] ); INC( i ); END; >some compilers might not optimize, and the expression will have to be >evaluated every time. Is it known that Length(s) is constant for the time duration of that loop? That is necessary before Length(s) can be optimized for use in testing the above WHILE condition. -- uucp: uunet!m2xenix!puddle!42.15!Jim.Long Internet: Jim.Long@p15.f42.n105.z1.fidonet.org