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)

Code: Copy
    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

Code: Copy
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.
Code: Copy
    Dim arrString(4) As String = Array As String("first","second","penultimate","lastOne")
 
Last edited:
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: Copy
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
 
This is in B4R - but thank you for trying the code.
 
Right. I missed that. Because of the complex handling of strings in B4R, I wouldn't be surprised if that is a real bug.
 
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
 

Similar Threads

Back
Top