Variables & Constants¶
CrossBasic uses variables to hold mutable data and constants to hold immutable values. This page covers how to declare, assign, and use both in your scripts.
Variables¶
Declaration¶
You can declare variables in two ways:
-
Explicit typing with
Dim
-
Type inference with
Var
Var total = 0 // inferred as Integer
Var title = "Hello" // inferred as String
Var win As New XWindow // explicit type when using New
Tip: If you omit
As Typewhen usingVar, CrossBasic infers the type from the initial value.
Assignment¶
Use the = operator or one of the compound assignment operators (+=, -=, *=, /=):
Dim x As Integer = 5
x = 10 // simple assignment
x += 2 // addition assignment (x = x + 2)
x *= 3 // multiplication assignment (x = x * 3)
Scope & Lifetime¶
- Local variables declared inside a
SuborFunctionlive for the duration of that procedure. - Module‑level variables declared at the top of a script file (outside any
Sub/Function) live for the lifetime of the program. - Global variables: Any module‑level
VarorDimis accessible from any procedure in that module. To share across modules, place in a shared “Globals.xs” script and import it.
Naming Rules¶
- Must start with a letter (A–Z) or underscore (
_). - May contain letters, digits (0–9), and underscores.
- Cannot use keywords (e.g.
If,Dim,Const). - Case‑insensitive (
MyVar≡myvar).
Constants¶
Constants are read‑only values that cannot be reassigned once set.
Declaration¶
Use the Const keyword:
Const MaxItems As Integer = 100
Const Pi As Double = 3.1415926535
Const WelcomeMsg As String = "Welcome to CrossBasic!"
Error: Trying to reassign a constant will produce a compile‑time error:
Use Cases¶
- Configuration values (e.g. file paths, version numbers)
- Mathematical constants (e.g. π, e)
- Fixed flags (e.g.
Const DebugMode As Boolean = False)
Best Practices¶
- Group related constants at the top of your script or in a dedicated “Constants.xs” file and use #Import to include them in your programs.
- Use ALL_CAPS or PascalCase for constant names to distinguish them from variables.