Const and Dim

information about SharpBASIC language elements
Post Reply
User avatar
frank
Site Admin
Posts: 51
Joined: Sun Nov 21, 2021 12:04 pm
Location: Netherlands
Contact:

Const and Dim

Post by frank »

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).

Code: Select all

' module level declaration
dim x: int;

main do
  x = 12;
  print(x);
end
Variables can be initialized (defined) upon declaration:

Code: Select all

' declaration and initial definition
dim x: int = 12;

main do
  print(x);
end
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:

Code: Select all

option strict;

const C = 12;         ' implicit int8 (smallest type)
dim x: int = C;       ' error, must be of type int8
However, it is allowed to explicitly set a constant’s type:

Code: Select all

option strict;

const C: int = 12;    ' explicit int
dim x: int = C;       ' OK
As with module-level declarations (see also global and extern), local constants and variables can also be declared using a is..end block:

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
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

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
Last edited by frank on Wed Mar 09, 2022 2:50 pm, edited 3 times in total.
Keep it simple!
Post Reply