const pre-processed? Bug?

Blitz3D Forums/Blitz3D Programming/const pre-processed? Bug?

Ross C(Posted 2011) [#1]
Hi there. I have just been sitting scratching my head for about 20 mins. I have stupidly been referencing const variable before they have been called. I haven't noticed any errors though.

When you set a variable as a Const, it seems to set all Const variables before the first line of code is even executed. Is this the correct way it should work? Not that i'm complaining!


Yasha(Posted 2011) [#2]
Huh, never noticed that.

It's counterintuitive, since Consts look like variables and variables are declared in order... but on the other hand, the other constant declarations (i.e. functions) work this way, so eh-why-not? (That the compiler performs constant folding optimisations shouldn't affect this since the compiler still has to recognise the name at compile-time, meaning it can treat it like any other variable or expression while parsing.)

I wouldn't call it a bug, since there's no way it can affect anything. It still gives you the "Consts cannot be assigned" message if you use the name incorrectly, so there's not much risk of confusion.

I suppose it lets you hide your private constants at the bottom of a library file where they wouldn't be confused for the public interface... even then, I'm not sure why you would want to do that (since they're constant, that's about as safe a public interface as you can get). Tidiness, maybe.

Last edited 2011


H&K(Posted 2011) [#3]
Is this the correct way it should work?
Correct me if this is wrong or sounds wrong, BUT doesn't the compiler replace all const with the value the const is?

That is, on one of the passes it replaces the name with a value? If it didn't do this then a Constant would just be a variable (whose value you didn't change), and no speed benefit would be gained.


Yasha(Posted 2011) [#4]
on one of the passes it replaces the name with a value?


Yes, but this shouldn't affect anything as far as parsing goes. Replacing the constant names with their values has to happen after the expressions are parsed, otherwise the compiler wouldn't be able to give coherent error messages if you tried to assign a new value to a constant (instead it would think you were assigning to a value, or possibly comparing since it uses the same symbol).

The observation really just means that constant names are apparently read in a separate pass, before variable declarations and expression statements.

Upon thinking about it, there is a good reason for this after all: since types and functions also get their own advance pass (i.e. you can use functions above their declaration too), constants need to be read before function definitions, so that you can use the constant name as a default value in parameter lists. With the consequence described above.