Bug? [Solved]In debug, re-using a variable previously used in a for declaration

alwaysbusy

Expert
Licensed User
Longtime User
Only in Debug mode (in release mode it is not a problem)!

When one uses a variable for a 'for' loop, you can't re-use it as a dim later

Error:
B4X:
B4J Version: 6.01
Parsing code.    (0.00s)
Compiling code.    Error
Error compiling program.
Error description: Current declaration does not match previous one.
Make sure to declare the variable before it is used in a For loop.
Error occurred on line: 17
Dim i As Int

Code to reproduce:
B4X:
'Non-UI application (console / server application)
#Region Project Attributes
   #CommandLineArgs:
   #MergeLibraries: True
#End Region

Sub Process_Globals
 
End Sub

Sub AppStart (Args() As String)
   For i = 0 To 10 ' <----- used the i variable
       Log(i)
   Next
 
   For k = 0 To 10
       Dim i As Int  ' <------ now using it 'normal', gives the error
       i = k
       Log(k)
   Next
 
   StartMessageLoop
End Sub
 

LucaMs

Expert
Licensed User
Longtime User
For I As Int = 0 to 10

and it should work.

You should always declare the type of variables.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
This is not a bug. As you can see in the error message the compiler tells you how to solve it.
This is a limitation related to a debugger optimization.

For I As Int = 0 to 10
You cannot set the type here.

The way to solve it is by declaring the variable before the For loop:
B4X:
Dim i as Int
For i = 0 To 10

Note that you don't need to always declare the variable before the for loop. In fact it is better not to.
This is only required when you first use a new variable in a for loop and later dim it.
 
Top