User Tools

Site Tools


variables

Variables

A variable in SharpBASIC can be any name that consists of the ASCII-characters A..Z, a..z, 0..9 and underscore, provided that the first character is a letter (A..Z or a..z). Names are case-sensitive, so a variable named 'text' is not the same as a variable named 'Text'. Variables can be declared with the statements dim and const.

DIM statement

A variable can be declared in the prologue section with a dim-statement, followed by the variable name, a colon and the variable's type. The statement ends with a statement terminator:

dim x: int;

Upon declaration variables can have an initial value assigned to them, but only an immediate value or a constant; they cannot be assigned an expression or a function:

dim x: int = 100;

Variables of the same type can be declared with a single statement using comma's:

dim x, y, z: int;

When declaring multiple variables in a single statement, they can all have the same initial value assigned to them:

dim x, y, z: int = 0;

Variables without initial value are uninitialized and can have any random value. This is important when for example a variable is used for iteration:

dim n: int;        ' uninitialized
main do
  n = n + 1;       ' not good
end
versus:
dim n: int = 0;    ' initialized
main do
  n = n + 1;       ' ok
end

CONST statement

With the statement const variables can be assigned a fixed value that cannot be changed throughout the program:

const msg_HelloWorld = "Hello World";

By default the compiler will figure out a constant's type based on the assigned value:

const num_X = 8;

Because the smallest type that fits the value 8 is a byte, num_X will be of type int8. However, a constant's default type can be explicitly set if so desired:

const num_X: int = 8;

Constants can be used to assign initial values:

const num_X: int = 8;     ' type int
const num_Y = num_X;      ' type int because num_X is of type int
dim x, y: int = num_Y;

variables.txt · Last modified: 2022/02/22 12:06 by admin