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

Brian G brian at westwoodsvcs.com
Tue Mar 28 03:08:19 CEST 2023


Hi Jussi, 

Surprisingly this completely invalid C code compiles and actuall works the same way as 
gambas. It remebers the value of p which goes out of scope between itterations.. lol 
But if you throw in a few other volitile declarations between it all goes to pot.... 

#include <stdio.h> 

int main() { 
printf("hello world\n"); 
int i,j,k,l; 
for(l=0; l< 2; l++) { 
for(k=0; k < 2; k++) { 
for(i=0;i<1000000;i++) { 
int p; 
p++; 
if(p % 1000000 == 0) printf("p=%d, j=%d\n",p,j); 
j=p; 
} 
printf("j=%d\n",j); 
} 
} 
} 
Output : 

hello world 
p=1000000, j=999999 
j=1000000 
p=2000000, j=1999999 
j=2000000 
p=3000000, j=2999999 
j=3000000 
p=4000000, j=3999999 
j=4000000 

This is a fun fact! But don't depend upon it! 

"Failure is the key to success; 
each mistake teaches us something" .. Morihei Ueshiba 
Brian G 

----- On Mar 28, 2023, at 12:42 AM, Jussi Lahtinen <jussi.lahtinen at gmail.com> wrote: 

> I think "Dim b As Integer" should be the same as "Dim b As Integer = 0". I
> consider this as a bug / unwanted feature.
> If "Dim b As Integer" is equal to a local variable declared at the beginning of
> a function/sub, then I think IDE should just move it there.

> In C variables "a" and "b" would be out of scope (valid only within the loop)
> and thus this would not compile and thus no confusion.

> Jussi

> ----[ http://gambaswiki.org/wiki/doc/netiquette ]----
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20230327/914afd8a/attachment-0001.htm>


More information about the User mailing list