Bug? For Each Loop

Daestrum

Expert
Licensed User
Longtime User
The For Each loop over an array of strings appears to be stopping one short (plus corruption of strings)

B4X:
    Log("***  for each  ***")
    For Each ss As String In returnStrings
        Log(ss)
    Next
    Log("***  for loop  ***")
    For tmp = 0 To returnStrings.Length - 1
        Log(returnStrings(tmp))
    Next
    Log("---Done---")

The routine they call

B4X:
Sub returnStrings() As String()
    Dim arrString(4) As String
    arrString(0) = "first"
    arrString(1) = "second"
    arrString(2) = "penultimate"
    arrString(3) = "lastOne"
    Return arrString
End Sub

The logs show
1615604769360.png


Note: dont try (unless you like stack dumps and eternal reboot loops) in the Sub returnStrings.
B4X:
    Dim arrString(4) As String = Array As String("first","second","penultimate","lastOne")
 
Last edited:

William Lancee

Well-Known Member
Licensed User
Longtime User
I just tried your code and two variants. They all work as expected in B4J. I suspect you have a name conflict of some kind.

B4X:
Sub AppStart (Args() As String)
     Dim arrString() As String = Array As String("first","second","penultimate","lastOne")
   
    Log("***  for each  ***")
    For Each ss As String In arrString
        Log(ss)
    Next
    Log("***  for loop  ***")
    For tmp = 0 To arrString.Length - 1
        Log(arrString(tmp))
    Next
    Log("---Done---")


    Dim x() As String = returnStrings
    For Each ss As String In x
        Log(ss)
    Next
    Log("***  for loop  ***")
    For tmp = 0 To x.Length - 1
        Log(x(tmp))
    Next
    Log("---Done---")

    For Each ss As String In returnStrings
        Log(ss)
    Next
    Log("***  for loop  ***")
    For tmp = 0 To returnStrings.Length - 1
        Log(returnStrings(tmp))
    Next
    Log("---Done---")
   
End Sub

Sub returnStrings() As String()
    Dim arrString(4) As String
    arrString(0) = "first"
    arrString(1) = "second"
    arrString(2) = "penultimate"
    arrString(3) = "lastOne"
    Return arrString
End Sub
 

Daestrum

Expert
Licensed User
Longtime User
This is in B4R - but thank you for trying the code.
 

William Lancee

Well-Known Member
Licensed User
Longtime User
Right. I missed that. Because of the complex handling of strings in B4R, I wouldn't be surprised if that is a real bug.
 

Cableguy

Expert
Licensed User
Longtime User
Strings are not recomended in B4R due to memory handling issues. The recommended way (if I'm not mistaken) is to convert the string to a byte array or to use serialization
 
Top