Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

#273 Initialize global variable from others

open
nobody
None
2013-06-02
2013-06-02
No

Generally it's not possible to initialize global variables with values from other variables. Only constants can be used.


Example with Integer:

Static As Integer I1 = 1234
Static As Integer I2 = I1
Static As String S1 = "Hello!"
Static As String S2 = S1

Print I1, S1
Print I2, S2

(2) error 11: Expected constant in 'Static As Integer I2 = I1'
(4) error 78: Var-len strings cannot be initialized in 'Static As String S1 = "Hello!"'
(5) error 11: Expected constant in 'Static As String S2 = S1'


But with UDT and constructors, that compiles and works:

Type UDT
  Dim As Integer I
  Dim As String S
  Declare Constructor (Byval i As Integer, Byref s As String)
  Declare Constructor (Byref u As UDT)
End Type
Constructor UDT (Byval i As Integer, Byref s As String)
  This.I = i
  This.S = s
End Constructor
Constructor UDT (Byref u As UDT)
  This.I = u.I
  This.S = u.S
End Constructor

Static As UDT U1 = UDT(1234, "Hello!")
Static As UDT U2 = U1

Print U1.I, U1.S
Print U2.I, U2.S

Output:
1234 Hello!
1234 Hello!


Indeed, it's possible to use global constructors that will be executed before the main part of the program to initialize global variables for which this is needed. That's what FreeBASIC does for global variables that have constructors.

For the first case, FreeBASIC could effectively do the same (using also global constructors principle) in order to initialize global variables from others, and then this case could be allowed. This technique could also be used to allow initialization of global dynamic strings.


Referring to forum at posts:
http://www.freebasic.net/forum/viewtopic.php?p=187820#p187820
http://www.freebasic.net/forum/viewtopic.php?p=187828#p187828

Discussion