Joseph Oswald wrote:
The attached program demonstrates an issue with Gnu Pascal, version 20030507. The program cannot be compiled because of a non-existent "threat" on the global loop variable used in a subroutine. The main program has a loop which uses the variable, but calls no subroutines within the loop, and therefore is not vulnerable to any threat from use of that variable by other subroutines.
Attempting to compile this program results in the message
gpc -o forwarning forwarning.pas forwarning.pas: In main program: forwarning.pas:13: error: `for' loop counter is threatened in a subroutine
The program contains an error involving a for loop and when fixed GPC compiles the program with no errors. The above error message, though, is pretty misleading as to real error in the program.
Both Pascal standards specify the following requirement for for-statements:
"The control-variable shall be an entire-variable whose identifier is declared in a variable-declaration- part of the block closest-containing the for-statement."
Thus the useloopvar subroutine as written is an illegal code construct since there is no declaration for the loopvar control variable in the useloopvar block which closest-contains the for-statement..
procedure useloopvar; {ERROR - no local var declaration for loopvar} begin for loopvar := 1 to 3 do writeln('useloopvar ',loopvar) end; { useloopvar }
The fix is to add a local var declaration for loopvar:
procedure useloopvar; var loopvar: integer; begin for loopvar := 1 to 3 do writeln('useloopvar ',loopvar) end; { useloopvar }
With the above add local var declaration, the program compiles, runs, and produces the expected out.
This usage is present in Donald E. Knuth's WEB and TeX programs, and requires changing these loops to use unique loop variables.
This isn't the first time nor will it be the last time when porting a program to a different compiler uncovers latent errors in a program. In the area of for-statements, there are latent errors in quite a few programs since there are quite a few compilers around which don't enforce all the for-statement requirements.
Gale Paeper gpaeper@empirenet.com