Article View: comp.lang.modula2
Article #4205Re: The semantics of the for-loop
From: Roger Crew
Date: Sun, 17 Apr 1988 21:34
Date: Sun, 17 Apr 1988 21:34
72 lines
2352 bytes
2352 bytes
In article <2455@pasteur.Berkeley.Edu> seitz@cory.Berkeley.EDU.UUCP
(Matthew Eric Seitz) writes:
>
> _Programming_In_Modula-2_ essentially defines the for statement as
> the following equivalency
>
> "FOR" ident ":=" expression1 "TO" expression2 [ "BY" ConstExpression ] "DO"
> StatementSequence
> "END"
> is equivalent to
>
> ident ":=" expression1;
> "WHILE" ident "<=" expression2 "DO"
> StatementSequence
> [ident ":=" ident "+" ConstExpression (* if "BY" clause used *) |
> ident ":=" ident "+ 1" (* if "BY" clause not used *) ]";"
> "END"
> (* ident := undefined *)
>
Ouch.
If _Programming_in_Modula-2_ says this,...
well, it's a mistake, plain and simple.
Consider:
FOR ch := 0C TO 255C DO
whatever
END;
which supposedly is equivalent to
ch := 0C;
WHILE ch <= 255C DO
whatever
INC(ch);
END;
If you don't like playing with characters, try FOR i := -2^31 TO 2^31-1
(for 32 bit integers... i.e., MININT and MAXINT, or whatever they happen
to be called these days...).
The WHILE loop will bomb at runtime when it tries to increment 255C.
If you were doing this with integers, you won't be this lucky.
(hint:
in C, for(ch=0;ch<=255;ch++) is an infinite loop when ch is an 8-bit char).
You really do need that second IF statement (or something similar;
if you don't like writing the statement body twice, then you have to
go through contortions like
ident := expression1;
IF ident <= expression2 THEN
LOOP
whatever;
IF ident = expression2 THEN EXIT END;
INC(ident);
END;
END;
And even this general form fails miserably for
FOR ch := 0C TO 255C BY 2 DO
whatever
END;
(unless, or course, you cheat by changing 255C to 254C)
--
Roger (crew@polya.stanford.edu) ``Beam Wesley into the sun!''
Technical Details
Message-ID:
<2633@polya.STANFORD.EDU>Path:
arc1-ca.pugleaf.net!utzoo!mnetor!uunet!lll-winken!lll-tis!ames!amdahl!pyramid!decwrl!labrea!polya!crewReferences:
<5571@uwmcsd1.UUCP> <2455@pasteur.Berkeley.Edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!mnetor!uunet!lll-winken!lll-tis!ames!amdahl!pyramid!decwrl!labrea!polya!crew From: crew@polya.STANFORD.EDU (Roger Crew) Newsgroups: comp.lang.modula2 Subject: Re: The semantics of the for-loop Message-ID: <2633@polya.STANFORD.EDU> Date: 17 Apr 88 21:34:52 GMT References: <5571@uwmcsd1.UUCP> <2455@pasteur.Berkeley.Edu> Reply-To: crew@polya.Stanford.EDU (Roger Crew) Organization: Stanford University Computer Science Dept. Lines: 71 Summary: FOR <> WHILE in Modula-2