Dim Statement

Top  Previous  Next

       

Function:

Defines a variable and allocates memory for it.

Syntax:

 

[ public ] dim name1 [ (bounds1) ] [ , name2 [ (bounds2) ] ]

as type [ (max_string_size) ]

Scope:

Global, HTML and local

See Also:

Declare Statement

 


Part

Description

public

Optional; may only be used in a global scope. If present, makes the variable(s) public.

name[1, 2...]

Required. Specifies the name for the variable.

bounds[1, 2...]

Optional. Specifies the boundary (finite size) of a dimension in an array. Several comma-delimited boundary values make a multi-dimensional array.

as

Required. Precedes the type definition.

type

Required. Specifies the type of the variable.

max_string_size

Optional (can be used only when type is string). Sets the maximum size for a string (default size is 255 bytes).

Details

The dim statement creates a variable in the current scope. It reserves memory space for this variable. Hence, as part of a dim statement, you have to specify the type of the variable; specifying the type also defines how much memory will be allocated for this variable.

When creating strings, you can explicitly define their maximum size by including it in parentheses immediately following the string keyword. The default maximum size of strings is 255 bytes, but if you're sure a string will contain less than 255 bytes of data, it is better to constrain it to a lower size (and thus reduce the memory footprint of your program).

The dim statement can also be used to create arrays. This is done by specifying the number of elements in the array in parentheses immediately following the name of the variable. Multi-dimensional arrays are created by specifying the number of elements in each dimension, separated by commas.

Note that creating a variable using dim does not assign any value (i.e, 0) to this variable.

There are alternative ways of specifying the number and size of each array dimension in an array. Please, examine the examples below.

Examples

 

dim x, y(5) as integer ' x is an integer; y is a one-dimensional array of 5 integers.

dim z(2, 3) as byte ' a two-dimensional array, 2x3 bytes.

dim z2(2) as byte(3) ' same -- a two-dimensional array, 2x3 bytes

dim z2 as byte(2,3) ' same again -- a two-dimensional array, 2x3 bytes

 

dim s as string(32) ' s is a string which can contain up to 32 bytes

dim s(10) as string(32) 'array of 10 strings with 32-byte capacity

dim s as string(32)(10) 'alternative way to make the same definition