B4J Question [SOLVED] unreachable statement, but I don't see it

alwaysbusy

Expert
Licensed User
Longtime User
I have a simple snippet (or so I thought) to truncate a sentence to a certain length, but keeping whole words.

For some reason the compiler says this statement is unreachable, but I can't see why. Extra set of eyes required...
B4X:
public Sub Truncate(s As String, len As Int) As String 'ignore
   If s.Length <= len Then
       Return s
   End If
   Dim suffix As String = Chr(0x2026)
   Dim words() As String = Regex.Split(" ", s)
   Dim ret As String
   Dim index As Int
   ' does not work:
   'Do While True
   ' Solution by Erel
   Do While Not(False)
       If (ret.Length + words(index).Length) < len Then
           ret = ret & words(index) & " "
           index = index + 1
           If index = words.Length Then
               Return ret.trim & suffix
           End If
       Else
           Return ret.trim & suffix   ' <----- unreachable statement if one uses Do White True
       End If
   Loop
End Sub

Alwaysbusy
 
Last edited:

alwaysbusy

Expert
Licensed User
Longtime User
Not all code paths return a value
yes, that is why I used the 'ignore. However, the error comes at compile time.

upload_2019-2-26_11-7-21.png
 
Upvote 0

Harris

Expert
Licensed User
Longtime User
Generally I Exit from loops before returning, but I see your point.

B4X:
public Sub Truncate(s As String, len As Int) As String 'ignore
   If s.Length <= len Then
       Return s
   End If
   Dim suffix As String = Chr(0x2026)
   Dim words() As String = Regex.Split(" ", s)
   Dim ret As String
   Dim index As Int
   ' does not work:
   'Do While True
   ' Solution by Erel
   Do While Not(False)
       If (ret.Length + words(index).Length) < len Then
           ret = ret & words(index) & " "
           index = index + 1
           If index = words.Length Then
              Exit  'jump out of loop...
           End If
       Else
           Exit
       End If
   Loop

   Return ret.trim & suffix
End Sub
 
Upvote 0
Top