Initialize static variables?

Everything else that doesn't fall into one of the other PB categories.
matthew180
User
User
Posts: 64
Joined: Mon Jun 30, 2003 5:36 pm
Location: Michigan
Contact:

Initialize static variables?

Post 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
User avatar
tinman
PureBasic Expert
PureBasic Expert
Posts: 1102
Joined: Sat Apr 26, 2003 4:56 pm
Location: Level 5 of Robot Hell
Contact:

Re: Initialize static variables?

Post 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.
If you paint your butt blue and glue the hole shut you just themed your ass but lost the functionality.
(WinXPhSP3 PB5.20b14)
Froggerprogger
Enthusiast
Enthusiast
Posts: 423
Joined: Fri Apr 25, 2003 5:22 pm
Contact:

Post 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
%1>>1+1*1/1-1!1|1&1<<$1=1
User avatar
NoahPhense
Addict
Addict
Posts: 1999
Joined: Thu Oct 16, 2003 8:30 pm
Location: North Florida

Post by NoahPhense »

Nice..

- np
matthew180
User
User
Posts: 64
Joined: Mon Jun 30, 2003 5:36 pm
Location: Michigan
Contact:

Post 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
Pupil
Enthusiast
Enthusiast
Posts: 715
Joined: Fri Apr 25, 2003 3:56 pm

Post by Pupil »

Static vars are initialized to zero like all other variables in PB, just look at the commented ASM output!
Post Reply