Path: utzoo!attcan!uunet!husc6!rutgers!mailrus!csd4.milw.wisc.edu!markh From: markh@csd4.milw.wisc.edu (Mark William Hopkins) Newsgroups: comp.lang.pascal Subject: Re: Control variables in FOR loops Message-ID: <45@csd4.milw.wisc.edu> Date: 21 Dec 88 22:48:39 GMT References: <1439@csuna.UUCP> Sender: news@csd4.milw.wisc.edu Reply-To: markh@csd4.milw.wisc.edu (Mark William Hopkins) Organization: University of Wisconsin-Milwaukee Lines: 80 In article <1439@csuna.UUCP> abcscnuk@csun.UUCP (Naoto Kimura) writes: > > I have gotten into some pretty heated discussions regarding the >control variable in a for loop. I was arguing that it was a bad idea to >use a global variable, in fact it is an error to do so. I'm arguing >from the ISO standard, while the people I was arguing against were going >by specific implementations that allowed it. You are right about its illegality. In any case, a programmer has no business cluttering up the "main program" with extraneous variables. It makes the program more difficult to read, and write. Some people even initialize the counters (gag). I think the only sensible approach to defining for loops is to make it equivalent to the corresponding while loop, much as in C. Example: for I := A to B do S equals I := A; while I <= B do begin S; if I < B then I := succ(I) end an optimized version would be this: I := A; while I < B do begin S; I := succ(I) end; if I = B then S > > I'd like to know how you feel about the behavior of the following >program. What should the output be (if the compiler even lets this >code through) ? > >program nonsense(input,output); > var > i : integer; > > procedure barf; > begin > for i := 1 to 10 do > write(i:3); > write(' i=',i) > end; According to the definition I posed above, the output would be: 1 2 3 4 5 6 7 8 9 10 i= 10. (assuming that the default integer field width is 10.) My definition makes the variable stay at 10. In general, this kind of thing is necessary if you are going to be able to handle for loops with subrange types and enumerated types correctly. > > procedure ack; > begin > for i := 1 to 10 do begin > write('i=',i:2,' '); > barf; > writeln > end > end; i= 1 1 2 3 4 5 6 7 8 9 10 i= 10. The only real argument here is that "barf" should be barf(i) (or i := barf). The missing parameter is at fault for the "unpredictability more so than the "faulty" counter. > >begin > for i := 1 to 10 do > ack >end. Same as ack, according to my definition above. Same argument too: "ack" should be ack(i), or better yet, i := ack. It's the unnecessary global variables that present the problem, not the counters.