Const and Dim
Posted: Mon Nov 22, 2021 11:23 am
The dim statement is used to declare and optionally define a variable of a specific type. Dim statements are allowed in the prologue section of a module, a subroutine or a function (this is always before a do..end statement).
Variables can be initialized (defined) upon declaration:
Initial definitions are limited to numeric and alphanumeric (string) literals (aka immediates), or constants (fixed references to immediates). It is not possible to assign a function or expression upon declaration. If a variable is assigned a constant, the variable type must match the constant type. With option strict enabled, types must match exactly:
However, it is allowed to explicitly set a constant’s type:
As with module-level declarations (see also global and extern), local constants and variables can also be declared using a is..end block:
Constants can be passed as argument to a subroutine or function, but they cannot be passed by reference. The following example generates a compile-error:
Code: Select all
' module level declaration
dim x: int;
main do
x = 12;
print(x);
end
Code: Select all
' declaration and initial definition
dim x: int = 12;
main do
print(x);
end
Code: Select all
option strict;
const C = 12; ' implicit int8 (smallest type)
dim x: int = C; ' error, must be of type int8
Code: Select all
option strict;
const C: int = 12; ' explicit int
dim x: int = C; ' OK
Code: Select all
sub test()
dim is
p: ptr;
n: int = 240;
m: uint8;
end
do
p = aof(n);
m = bya(p);
print(m);
end
Code: Select all
decl sub test(ref a: uint8);
const C = 15;
main
do
test(C); ' error: passing constant by reference
end
sub test(ref a: uint8)
do
a = a + 240;
end