Android Tutorial For vs. While

While usually interchangeable, we should all be aware of one very important difference between these two cycles.
The For...Next cycle caches the "goal", the Do...Loop does not.

XcOG7UR.png


M0ScnuY.png


Happy coding! :)
 

thedesolatesoul

Expert
Licensed User
Longtime User
I dont know if that is a B4A or Java compiler optimization, but did you try returning a different value from the function? (For e.g. return a random number?)
In a for loop, the termination condition has to be evaluated on every iteration, i.e. is i < OneHundredThousand(i), but since the function returns a static value it is possible the compiler optimized it.
 

thedesolatesoul

Expert
Licensed User
Longtime User
I know.
Just to clarify this 'feature' is inherent to B4X, this is not a Java feature.
During translation from (for e.g.) B4J to Java, the bounds are cached.
Personally, I think this is an incorrect design decision. The decision to cache the bounds should be left to the developer, not the language.

Imagine:
B4X:
Sub AppStart (Args() As String)
    Dim i = 1 As Int
    For i = 1 To OneHundredThousand(i)
    Next
    Log("for loop completed " & i)
End Sub

Sub OneHundredThousand(i As Int) As Int
    Dim s As Char
    If i > 1 Then s = "s"
    Log("This function was called " & i & " time" & s)
    Return i+5
End Sub
 

MaFu

Well-Known Member
Licensed User
Longtime User
For the most languages the upper bound is evaluated only on loop start, this is the normal behaviour of the for loop. If a bounds recalculation is needed then a while should be used.
 

MaFu

Well-Known Member
Licensed User
Longtime User
Maybe it was a hasty conclusion. I name it "normal" only in relation to "most languages". But also many languages use the other way and evaluate on every loop cycle.

You think it's an incorrect design decision because java evaluates on each cycle. But B4X is Basic and in Basic the evaluation is only done at loop start. Therefore it is correct implemented.
Only my opinion.
 

thedesolatesoul

Expert
Licensed User
Longtime User
Maybe it was a hasty conclusion. I name it "normal" only in relation to "most languages". But also many languages use the other way and evaluate on every loop cycle.

You think it's an incorrect design decision because java evaluates on each cycle. But B4X is Basic and in Basic the evaluation is only done at loop start. Therefore it is correct implemented.
Only my opinion.
The way you wrote it sounded like a fact, which is why I questioned you. I think the keyword in your post is 'opinion'.
I'm still disappointed you didnt name many languages, atleast I would have learnt something. Do you have some source or link, atleast I'd like to see which 'Basic' you are talking about?
 
Top