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¶
- Local Scope
- Parameters and variables declared inside a Function/Sub are local to that routine.
-
They disappear when the routine returns.
-
Module/Global Scope
-
Routines and
Dim/Vardeclarations at the top level of a module are accessible from anywhere in that module (and, ifPublic, from other modules). -
Nested Calls
- Each call to a routine gets its own environment (stack frame).
- 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 .