Sub TestByteLoop
Dim i As Byte
Dim arrBytes(128) As Byte
For i = 1 To 127
Log(i)
arrBytes(i) = i '<< how can i go past 127 here?
Log(arrBytes(i))
'If i = 127 Then Exit 'this fixes it, but why is it needed?
Next
End Sub
Sub TestByteLoop
Dim i As Byte
Dim arrBytes(128) As Byte
For i = 1 To 127
Log(i)
arrBytes(i) = i '<< how can i go past 127 here?
Log(arrBytes(i))
'If i = 127 Then Exit 'this fixes it, but why is it needed?
Next
End Sub
Sub TestByteLoop
Dim i As Byte
Dim arrBytes(128) As Byte
For i = 1 To 127
Log(i)
arrBytes(i) = i '<< how can i go past 127 here?
Log(arrBytes(i))
'If i = 127 Then Exit 'this fixes it, but why is it needed?
Next
End Sub
I am using that and it is very useful, but not sure how that answers the question. I understand that byte is poor choice for a loop iterator, but how does i become -128 if the loop limit is set at 127?
Bytes are signed values in Java/B4X so have a maximum positive value of 127 and a minimum negative value of -128. The loop exits when the loop counter is incremented past the limit. If you increment a byte value of 127 it overflows to -128.
Bytes are signed values in Java/B4X so have a maximum positive value of 127 and a minimum negative value of -128. The loop exits when the loop counter is incremented past the limit. If you increment a byte value of 127 it overflows to -128.
Yes, I understand that, but why does it enter one more iteration if the iterator has already reached 127?
You can see this if you step through the code in debug mode.
The test for exiting the loop is greater (or less) than, not equality. The counter is incremented (or decremented) at the end of the loop and the test then made whether to continue the loop or not.
The test for exiting the loop is greater (or less) than, not equality. The counter is incremented (or decremented) at the end of the loop and the test then made whether to continue the loop or not.
Sub TestByteLoop
Dim i As Byte
Dim arrBytes(128) As Byte
For i = 1 To 127
Log(i)
arrBytes(i) = i '<< how can i go past 127 here?
Log(arrBytes(i))
'If i = 127 Then Exit 'this fixes it, but why is it needed?
Next
End Sub
The loop is ok but you can't store a value >127 in a byte. So when you need to fill all 255 possible values make a loop from 0 to 254 and subtract 127 from i. Vice versa add 127 to the value to get unsigned bytes.
You can create a byte array as long as you want but the VALUES in it can be from -127 to +127. 127+127+0=255 different values unsigned.
I copied it from a bit of real code where array element 0 needed to be untouched.
The Sub as posted doesn't do anything and all the array elements remain unused.