FOR...NEXT creates it's own variable and then destroys it?

Previous topic - Next topic

Cliff3D

This code compiles without any warning or error and runs (quite quickly!):

Code (glbasic) Select
// --------------------------------- //
// Project: forNext
// Start: Thursday, September 16, 2010
// IDE Version: 8.085


// FREE-VERSION:
// Need Premium for Features:
// 3D Graphics
// Network Commands
// INLINE C/C+++ code

// SETCURRENTDIR("Media") // seperate media and binaries?

FOR temp% = 1 TO 3
NEXT


even though the variable "temp%" has not been declared/defined.

Add a line that uses the FOR...NEXT variable (temp%) outsid eof the loop though, like this:

Code (glbasic) Select
FOR temp% = 1 TO 3
NEXT
DEBUG temp%


...and you get the standard "variable not declared" error when you try to compile:

Quote*** Configuration: WIN32 ***
precompiling:
GPC - GLBasic Precompiler V.8.044 SN:1fd6eb1b - 2D, WIN32
"forNext.gbas"(17) warning : probably unassigned variable : temp
"forNext.gbas"(17) error : variable is not explicitly defined : temp

this isn't a critical error, but does seem rather odd to me that you can use a variable tha tisn't defined in some instances, but not in others :(

ketil

Since the code is converted to C++, i guess the for next loop is converted to this:

for(int temp=1; temp < 4; temp++){}

The variable temp is then only accessible in the for/next - scope.
That is not an error.

The error is trying to use temp outside the for/next loop.
"Sugar makes the world go 'round. Caffeine makes it spin faster."

ketil

Also ...

Space for this variable (temp%) is statically allocated by the compiler, and not dynamically by runtime.
The object is therefore actually not destroyed.
The speed of the code should be the same as if it's decleared outside the loop as LOCAL.
"Sugar makes the world go 'round. Caffeine makes it spin faster."

Kitty Hello

That is on purpose. The new compiler in V8 creates a temp variable for the FOR index - which is handy. You don't need a LOCAL for that anymore.
If there is a local, that one should be used, though.


MrTAToad

Dont forget the variable only exists for the life of the loop...

Cliff3D

Quote from: MrTAToad on 2010-Sep-16
Dont forget the variable only exists for the life of the loop...

Yup - that's how I found out about this "locality" - by trying to use the result!