Skip to content

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:

  1. Explicit typing with Dim

    Dim count As Integer
    Dim name  As String = "Alice"
    Dim flag  As Boolean = True
    

  2. 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 Type when using Var, 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 Sub or Function live 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 Var or Dim is accessible from any procedure in that module. To share across modules, place in a shared “Globals.xs” script and import it.
' Globals.xs
Dim AppVersion As String = "1.0.0"

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

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:

MaxItems = 200  ' ❌ Invalid: cannot assign to a Const

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.
' Constants.xs
Const DefaultFontSize As Integer = 14
Const ColorRed        As Integer = &cFF0000