ZBasic Language Reference
84
ZBasic Microcontrollers
{Public | Private | Dim} <name>[(<dim-list>)] As <type> Based <base-expr>
As with normal variables, Dim has exactly the same effect as Private. Within a subroutine, a function
or any block structure, a local based variable may be defined using the syntax shown below.
Dim <name>[(<dim-list>)] As <type> Based <base-expr>
In both cases the <base-expr> element is an integral expression that gives the base address of the
variable. Some examples will help clarify the concept.
Dim bv as Byte Based &H100
This defines a Byte variable whose address is a constant value.
Dim addr as Integer
Dim bv as Byte Based addr
This defines a Byte variable whose address is given by the value of the Integer variable addr.
Dim addr as Integer
Dim sel as Byte
Dim fv as Single Based addr + CInt(sel * 3)
This defines a Single variable whose address is given by the value of an expression.
Dim addr as Integer
Dim bv as Byte Based addr.DataAddress
This defines a Byte variable whose address is constant - the same as the address of the variable addr.
Except for one important aspect, this has exactly the same effect as the following code.
Dim addr as Integer
Dim bv as Byte Alias addr
The difference between an alias and a based variable is how they are handled by the compilers
optimizer. Normally, when a variables value is referenced, the compilers optimizer attempts to deduce
the variables value at that point and, if it is more efficient to do so, the compiler will generate code using
the deduced value instead of the variables value in memory. However, if a variable is an Alias or has an
Alias that refers to it, the compiler may not attempt to make this optimization.
In contrast, the compiler does not attempt to determine if a based variable might be occupying the same
space as a normal variable. Consequently, if a variables value is changed by assigning to a based
variable that occupies the same space, the compiler may generate code that is incorrect. To circumvent
this potential problem, you may instruct the compiler not to make any assumptions about the value of a
variable by using the Volatile attribute as in the following example.
Dim Volatile addr as Integer
Dim bv as Byte Based addr.DataAddress
When defining an array variable that is Based, you may omit the <dim-list> element. In this case, the
compiler will assume that the array is one-dimensional, that its lower bound is 1 and that its upper bound
is a large value.
Dim addr as UnsignedInteger
Dim ba() as Byte Based addr
It is also permissible to define a based Persistent Memory or Program Memory variable. This is
accomplished by using the normal syntax for defining a persistent/program memory variable and
appending the Based keyword together with an address expression.
|