[Gambas-user] Variable reinitialized at each iteration of a loop structure

Brian G brian at westwoodsvcs.com
Tue Mar 28 01:00:56 CEST 2023


I have a question... as usual.. 

When a variable is declared within a loop with an initial value, the value is reinitialized at each iteration of the loop. 
But when it is not provided with an initial value,it is not reset to zero at each iteration of the loop or when the loop is entered. 

If we view each loop structure as a closed block of code, would it not be more appropriate to initialize the variable upon entry to the block. And then have the loop structure return to just after the initialization sequence rather than the actual loop entry label. 

Also should not the variable declared in the block without an initial value be reinitialized to the default value as the block is entered. 

I do understand that the declaration of a variable within any block is for convenience, but if it is allowed should their values not follow some consistent rules? 

How hard is it to change the return/iteration point on a loop to just after variable initialization of contained variables? 
Or maybe I am just wrong about this? 

Following is a script which illustrates the quandry: 
____________________________________________________________________ 
#!/usr/bin/env gbs3 
' Gambas Script File Created 03/27/2023 15:11:08 
for y as integer = 0 to 2 
for i as integer = 1 to 1000000 
dim a as integer = 1 
inc a 
next 
print "a=";a 
next 

for y = 0 to 2 
for i = 1 to 1000000 
dim b as integer 
inc b 
next 
print "b=";b 
next 

Quit 0 
Catch 
error "Script Error >";;error.text & "\n" & error.where 
________________________________________________________________________ 
Output Example: 
____________ _____________________________________________________________ 

a=2 
a=2 
a=2 
b=1000000 
b=2000000 
b=3000000 
__________________________________________________________________________ 

"Failure is the key to success; 
each mistake teaches us something" .. Morihei Ueshiba 
Brian G 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20230327/c1d016d1/attachment-0001.htm>


More information about the User mailing list