Page 1 of 1
Initialize static variables?
Posted: Fri Feb 25, 2005 9:33 pm
by matthew180
Greetings,
Is it possible to initialize static variables? If so, what is the syntax. If not, are static variables
guaranteed to be set to an initial value, like zero?
This is what I'd like to be able to do:
Code: Select all
Procedure something()
Static a.l = 0 ; Initial value.
...
EndProcedure
Matthew
Re: Initialize static variables?
Posted: Sat Feb 26, 2005 4:55 pm
by tinman
All variables are set to zero by default. However, it would be nice to be able to initialise static ones to something else.
Posted: Sun Feb 27, 2005 5:35 pm
by Froggerprogger
You could do it this way:
Code: Select all
Procedure MyProc()
Static a.l, b.l, c.l
Static isInitialized.l
If isInitialized = 0
a = 992
b = 12*a
c = 111
isInitialized = 1
EndIf
; some code
EndProcedure
Posted: Sun Feb 27, 2005 5:45 pm
by NoahPhense
Nice..
- np
Posted: Mon Feb 28, 2005 12:57 am
by matthew180
Froggerprogger wrote:You could do it this way:
Code: Select all
Procedure MyProc()
Static a.l, b.l, c.l
Static isInitialized.l
If isInitialized = 0
a = 992
b = 12*a
c = 111
isInitialized = 1
EndIf
; some code
EndProcedure
Correct, I can do that
if I know for certain that PB sets up all static vars to zero. If not, the first time the function is called the values for all static vars (including isInitialized) would be undefined. A simple test such as the code you present
might indicate that statics are set to zero, but this would only be an assumption until Fred says otherwise... And I can't rely on an assumption. Static vars being set to zero (or "" in the case of strings) is not documented, thus subject to change at any time.
Also, not being able to set those values at compile time means that the isInitialized check has to be performed every time the function is called and is unnecessary overhead.
Matthew
Posted: Mon Feb 28, 2005 9:16 am
by Pupil
Static vars are initialized to zero like all other variables in PB, just look at the commented ASM output!