Bug? compile bug with constants referenced before declaration?

Dave O

Well-Known Member
Licensed User
Longtime User
In sub class_globals (perhaps in activities too, haven't tried that yet), if I dim a variable and immediately set it to the value of a constant that is declared further down in that sub:
- the code compiles without errors or warnings
- the variable is set to zero (not to the constant's initial value in its declaration).

For example:
B4X:
Private Sub Class_Globals
   Private internalBackgroundColor As Int = DEFAULT_BACKGROUND_COLOR
   Public Const DEFAULT_BACKGROUND_COLOR As Int = Colors.ARGB(190, 0, 0, 0)
   'internalBackgroundColor is now zero, not the color above

I assume this is because, at the time of declaring the variable, the constant has not been declared yet, so its value is zero.

However, because there was no compiler error/warning, I missed it completely. Later, when I looked at the code, I assumed that it was doing some kind of multiple-pass compile where order didn't matter in this case, because it wasn't complaining about an undeclared constant.

Apparently order DOES matter (as it should), but I think it would be helpful for the compiler to raise an error (or at least a warning) that I'm referencing a constant that doesn't (yet) exist. That way, if I mistakenly declare a constant after a variable that uses it, I get warned immediately instead of blundering around later.

In the meantime, I've done what I should have done in the first place to make my code work - declare my constants first. :)
 
Last edited:
Top