[Gambas-user] Variable reinitialized at each iteration of a loop structure
Jussi Lahtinen
jussi.lahtinen at gmail.com
Tue Mar 28 05:14:51 CEST 2023
This is quite expected (and you got a bit lucky) as you do not initialize
"p", nor you are asking the value of "p" outside of the scope, instead you
print it inside the loop.
Normally compilers will give you warning about this, because uninitialized
values may not be zero like in Gambas.
So, at some not so lucky run value of "p" may start from some seemingly
random number.
Jussi
On Tue, Mar 28, 2023 at 4:15 AM Brian G <brian at westwoodsvcs.com> wrote:
> 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 ]----
>
>
> ----[ http://gambaswiki.org/wiki/doc/netiquette ]----
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20230328/63ef5148/attachment.htm>
More information about the User
mailing list