How BlitzCC handles Const

Blitz3D Forums/Blitz3D Programming/How BlitzCC handles Const

Ken Lynch(Posted 2003) [#1]
How does the Blitz compiler handle constants? I'm just asking because I was building up some useful constant libraries, such as scancodes and collision related constants. I was wondering, does each call to Const create a variable or does the compiler hard code the constants? If it creates variables then programs that use my libraries would contain a lot of redundant variables.

Anyone know?


Beaker(Posted 2003) [#2]
They are converted to hard coded values. In the same way that 30 in:
a=30
..is hard coded, or:
Data 30


Ken Lynch(Posted 2003) [#3]
But are they ALL hard coded? Or is the compiler clever enough to ignore ones that are not used?


fredborg(Posted 2003) [#4]
As far as I know it simply replaces the constant variable with the value held by it. ie:
Const a = 32
Const b = 15
Print a
Becomes:
Print 32
So I think only the ones that are actually used have any impact on the program.

Interesting fact: A constant can actually be overwritten locally by functions:
Const a = 32
Print a
Print NotSoConst(16)
Function NotSoConst(a)
  Return a
End Function
And the same goes for global variables.

Fredborg


Ken Lynch(Posted 2003) [#5]
Oh good. I was hoping they worked like that. Thanks.


Hotcakes(Posted 2003) [#6]
If they worked like variables, what would be the point of naming them Constants? ;]


soja(Posted 2003) [#7]
Hotcakes, you have a point. (I was wondering the same thing.) =)

Fredborg, that makes sense.
I also wish to elaborate on your interesting fact. The variable "a" from the function is NOT the same as the constant "a". The "Return a" statement returns the "a" that is MOST local in scope, which is the "a" declared in the function declaration. (You can see that nothing happens to the constant "a" by putting "Print a" after the function call.)

In a nutshell, variables declared within functions are active only in that function, even if they have the same name as a global or const. The compiler does differentiate them (i.e. they don't have the same name to the compiler).

I know you know this, I presume it's what you meant by being "overwritten". I just wanted to elaborate for those who didn't know why that was.