Skip to content

Scope & Recursion

Understanding how CrossBasic manages variable and routine scope is key to writing correct and reusable code—especially when you call functions from within other functions (recursion).


Scope Rules

  1. Local Scope
  2. Parameters and variables declared inside a Function/Sub are local to that routine.
  3. They disappear when the routine returns.

  4. Module/Global Scope

  5. Routines and Dim/Var declarations at the top level of a module are accessible from anywhere in that module (and, if Public, from other modules).

  6. Nested Calls

  7. Each call to a routine gets its own environment (stack frame).
  8. Local names do not conflict across calls, enabling recursion.

Example: Local vs. Global

Dim x As Integer = 10

Function Foo() As Integer
  Dim x As Integer = 5  // shadows global x
  Return x
End Function

Print(Foo())   // Prints 5
Print(x)       // Prints 10

Recursion

A function can call itself. Each call creates a new set of local parameters.

Example: Factorial

Function Factorial(n As Integer) As Integer
  If n <= 1 Then
    Return 1
  Else
    Return n * Factorial(n - 1)
  End If
End Function

Print(Factorial(5))   // Prints 120

Here, Factorial calls itself with n - 1 until the base case n <= 1 is reached.


Runtime Model

Under the hood, each call’s parameters and local variables live in a separate environment (stack frame). The bytecode VM pushes a new environment for each call and pops it on return, so recursion and nested calls behave exactly as in languages like C# or Java .