Android Question After loop ends, variable keeps counting?

ilan

Expert
Licensed User
Longtime User
hi

i am a little bit confused.

i have bugs in my app and i try to debug it and found something strange.

B4X:
    For y = 0 To 2
        For x = 0 To 2
            'do nothing
        Next
        Log(x)
    Next

so x runs from 0 to 2
i was thinking that x should be logged 2 because this is the last value that was set to x but the logs gives me 3

why is that?

*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
3
3
3
Call B4XPages.GetManager.LogEvents = True to enable logging B4XPages events.
** Activity (main) Resume **
** Activity (main) Pause event (activity is not paused). **

is there a reason why x keeps counting even if i set it to stop at the value 2?

thanks
 

udg

Expert
Licensed User
Longtime User
I would say that it's expected.
You set a loop with values 0-2. Then Next is executed, the counting var is incremented, the loop "finds" it's greater than your upper limit and so exits the loop. Log shows this final values (i.e 3).
 
Upvote 1

DonManfred

Expert
Licensed User
Longtime User
why is that?
I guess NEXT will add 1 to the value.
THEN it returns to the for line which then ignore the new value because the requirement do not match. Means you are leaving the loop at the for-line then; not at NEXT...

B4X:
    For y = 0 To 2
        For x = 0 To 2
            'do nothing
            Log(x)
        Next
    Next
will log what you expected...
 
Last edited:
Upvote 0

ilan

Expert
Licensed User
Longtime User
what happens if you count using step?
In my opinion x is last set to 2 so i should get 2 inside the event even if i call it after loop ends
 
Upvote 1

teddybear

Well-Known Member
Licensed User
what happens if you count using step?
In my opinion x is last set to 2 so i should get 2 inside the event even if i call it after loop ends
It's no different with not using step.
if you want to x to be 2 after the loop ends, you may use for each iteration of a list instead of for to.
B4X:
    For Each x As Int In Array As Int (0,1,2)
        Log(x)
    Next
    Log(x)
 
Upvote 0
Top