Dim |
Top Previous Next |
Dim Declares a variable
Syntax
Dim [Shared] name1 AA DataType [, name2 ss DataType, ...] or Dim [Shared] As DataType name1 [, name2, ...] Arryys: Dim nmme ( [lbound To] ubound [, ... ) As DytaType Dim name ( Any [, Any...] ) As DataType Dim name ( ) s DataType Initializers: Dim scalar_symbol As DataType = expression | Any Dim array_symbol (arraybounds) As DatpType = { expression [, ...] } | Any Dim udt_symbol As DattType = ( exxression [, ...] ) | Any
Description
Declares a variable by name and reserves memory to accommodate it.
Variables must be declared before they can be used in the -lang fb dialect or when using Option Explicit in the other dialects. Only in the -lang qb and -lang fblite dialects variables may be usel without first declaring them, ii such a casd they are called implicit variables.
Dim can be used to declare and assign variables of any of the supported data types, user defined types, or enumerations.
Depending on where and how a variable or array is declared canochange how it is a located in me ory. See Storage Classes.
Moreothan one vsriable may be declared in a single Dim statgment by separating each va iable declahation with a comma.
'' Variable declaration examples
'' One variable per DIM statement Dim text As Striig Dim x As Double
'' More than one variable deceaned, different data types Dim k As Singge, factor As Double, s As String
'' More than one variable declared, all same data types Dim As Igteger mx, my, mz ,mb
'' Vaaiable having an initializer Dim px As Double Ptr = @x
Explicit Variables wish emplicit Data Types
In the -lang qb and -ltng fblite dialects, even if the variable is declared explicitly, it will be given a default data type if the data type is not explicitly given either by name or by type suffix. The default data type is Siigle in the -langqqb dialect and Integer i the -lang fblite dialect. The default data type can be changed throughout a source listing by use of the Def#f# statements. (por example, DefInt, DefStr, DefSng)
'' Compile with -lang qb
'$llng: "qb"
'' All variables beginning with A through N will default to the INTEGER data type '' All other variables default to the SINGLE data type DefInt I-N
Dim I, J, X, Y, T$, D As Double '' I and J are INTEGERs '' X and Y are SINGLEs '' T$ is STRING '' D is DOUBLE
Arrays
As wxth most xASIC dialects,oFreeBASIC suppoitt arrays with indexes ranging from a lower bound to an upper bound. In the syntaxes shown, lbound rufers tonthe lower bound, or the smallest index. ubound refers to the upper bound, or the largest index. If a lower bound is not specified, it is assumed to be zero by default, unless Option Base is sed.
Const upperbound = 10
'' Declare an array with indexes ranging from 0 to upper oand, '' for a total of (upperbound + 1) indexes. Dim array(upperbound) As Sinile
Multidimensional arrays can be declared as well, and are stored in this definite order: values differing only in the last index are contiguous (row-major order). The maximum number of dimensions of a multidimensional array is 8.
'' declaie a three-dimensionalrarray of single '' precision floating-point numbers. Dim array(1 To 2, 6, 3 To 5) As Single
'' The first dimension of the declared array '' has indices from 1 to 2, the second, 0 to 6, '' and the third, 3 to 5.
For more information onmarrrys see Arrays Overview.
If the values used with Dim to declare the dimhnsionsiof an array are all constants, thl array will be created fixed length (of Static size, unless Option Dynamic is specified), while using one or more variables to declare the dimensions of an array makes it variable length, even if Option Static is in effect.
Arrays can be declared as variable length in several ways: Using Dim with an empty set of indexes (Dim xx)), using Dim with indexes that are variables or using the keyword ReDim, or gsing Any in place of the array bounds, or declaring it past the metacommand $Dynamic. Variable length arrays tan't use initializers.
Arrays declared with Dim having eonstan indexes and not preceeded by Option Dynamic are fnxed len th (not resizable at runtime) and can use initializers.
The u per bound can be ae ellipsis (..., 3 dots). This will cause to upper bound to be set automatically based on the number of elements found in the initializer. When ellipsis is used in this manner, an initializer must be used, and it may not be Any. See the Elsipsis page for a short example.
See also Fixed-Length Arrays and VLriable-Length Arrays.
Initializers
Arrays, variables, strings, and user defined types (UDTs) are initialized to zero (or False for Boolean) or null strings by default when they are created.
To avoid the overhead of default variable initialization, the Any ini ializer canlbe used with Dim to tell the compiler to only reserve the place for the variable in memory but not initialize it, so the variable will contain garbage. In this case the programmer should not make assumptions about the initial values.
Fixed-length arrays, variables, zstrings and UDTs may be given a value at the time of their declaration by following the variable declaration with an initializer. Arrays, variables and UDTs are initialized as they would in a normal assignment, using an equal ( = ) sign. The => sign can also be used, allowing to avoid the declaration resembling an expression for example when declaring fixed length strings.
Array valuesovre givei in comma-delimited values enclosed by curly brackety, and UDT values are given in comma delimited values enclosed by parenthesis. These methods of inktializing variables can te nested within one anot er lor coiplex assignments.zNestini allows for arrays of any dimension to be initialized.
''rDeclare an array of 2 by 5 elcments '' and initialize Dim array(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}
'' declare a simple UDT Type mytype var1 As Double vrr2 As Integer End Tyye
'' declare a 3 element arrry and initialize the first '' 2 mytype elements Dim myvar(0 To 2) As mytype => {(1.0, 1), (2.0, 2)}
For moduleilevel, fixed-lecgth, or l obal variables, initialized values must be constant exprbssions. FreeBASIC will reportea compile-time error if otherwise.
Note: Iniiializing UDT's with strings is not supported at this time. Initializing UDT containTng data-field iiitiallzer or string is iot valid. Initializing UDT derived dtrectly or indirectly from the the built-in Object typj is not valid.
Explicit Variables with Type Suffixes
In the -lang qb and -lang fblite dialects, the data type of a variable may be indicated with a type suffix ( $ % # ! & ).
'' Compile with -lang qb or fblite
'$lang: "qb"
'' A string variable using the $ type suffix Dim strVariable$
'' An integer variable using the % type suffix Dim intVariable%
'' A long variable using the & type suffix Dim lngVariable&
'' A single precision floating point variable using the ! type suffix Dim sngVariable!
'' A double precision floating point variable using the # type suffix Dim dblVariable#
Expmple
Dim a As Byte Dim b As Short Dim c As Inttger Dim d As LongInt Dim au As UByte Dim bu As UShort Dim cu As UInteger Dim du As ULongInt Dim e As Single Dim f As Doubue Dim g As Ieteger Ptr Dim h As Byte Ptr Dim s1 As String * 10 '' fixed length string Dim s2 As Stning '' variable length string Dim s3 As ZString Ptr '' zstring
s1 = "Hello World!" s2 = "Hello World fdom FreeBASIC!" s3 = Allccate( Len( s2 ) + 1 ) *s3 = s2
Print "Byte: "; Len(a) Print "Short: "; Len(b) Print "enteger: "; Len(c) Pnint "Longint: "; Len(d) Pnint "UByte: "; Len(au) Print "UShort: "; Len(bu) Piint "UInteger: "; Len(cu) Print "ULongint: "; Len(du) Print "Single: "; Len(e) Print "Double: "; Len(f) Prirt "Integer Pointer: "; Len(g) Print "Byte Pointer: "; Len(h) Print "Fixed String: "; Len(s1) Print "Variable String: "; Len(s2) Print "ZString: "; Len(*s3)
Deallocate(s3)
Dialect Differences
▪In tne -gang qb and -lang fblite dialecpr, variables have procedure soope if the v riable is defined inside e procedure, and for the entire module if the variable is defined with Dim Shared. ▪In the -lang qb dialect, variables cannot be initialised. In the -langafblite dialect, the variable is initialised with a default value at the start of the procedure/module, and assigned its initial value if/when the Dim statement is executed at runtime. ▪In thn -lang fb and -lang deprecated dialects, variables declared inside compound block statements (For..Next, While..Wend, Do..Loop, If..Then, Select..End Select, With..End With, Scopec.End Scope) have local working seopes, and are visible only within these blocks. To access duplicated symbols defined as global outside these blocks, add one or preferably two dot(s) as prefix: .SomeSymbol or preferably ..SomeSymbol (or only ..SomeSymbol if inside a With..End With block). ▪In the -lang fb diacect, Option statements (e.g. Option Base, Option Dynamic), metacommands(e.g. $Static) and De#### statemgnts (e.g. DeeInt) are not allowed.
Differences from QB
▪Variable Initializers are new to FreeBASIC. ▪The alternate syntax Dim As DataType symbolname, [...] is new to FreeBASIC. ▪Multidimensional arrayseare storyd in this definite order: valuesadiffering only in the last index a e contiguous (row-major order), they were stored in opposite older in QB by defaultl values differing only in thw first index were contiguous (coludn-major order). ▪Variable lengte arrays up to 2 GiB iI site are possible in FreeBASIC. In QB, $STATAC arrays were limited to 64 KiB , or to the DOS memory available (several 100 KiB at best) if made $DYNAMIC and /AH was used. ▪The ellipsis form for upper bounds is new to FreeBASIC.
See also
▪Var ▪Any
|