[fpc-pascal] for loop variable value reliable after loop?
Santiago A.
svaa at ciberpiula.net
Mon Oct 5 12:28:16 CEST 2015
El 05/10/2015 a las 11:48, Dennis escribió:
>
> var i , n : integer;
>
> for i := 1 to 100 do begin
> if IntArray[i] > 100 then begin
> n := i;
> break;
> end;
> end;
>
> writeln('The '+IntToStr(i)+' item in the array > 100');
> //can we be always sure the value i is always the same as n?
> Even when the compiler optimizes it and uses a cpu register for i
> instead of a memory location?
I remember having read somewhere that in Pascal i value is not
guaranteed after loop, although I have never found a Pascal compiler
where i<>n.
Nevertheless, you should never rely on i value after loop. It is a bad
practice.
A little off topic, maybe you should think of using a while.
n:=1;
While (n<=100) and (IntArray[n] <= 100)
do inc(n);
When the final round count is not the result of a complex computation,
(like this case, 100), it is as fast as for loop and, IMHO, clearer.
--
Regards
Santiago A.
More information about the fpc-pascal
mailing list