Variable Scoping describes where a variable is accessible, or available, within a program.
A BASIC Anywhere Machine program may declare (explicitly or implicitly) variables in:
- the main part (aka at a "global" level) of a program
- any subroutine / function (aka at a "local" level) in a program
Aside:
- A variable is implicitly declared via an assignment statement (whether using the LET keyword or not)
- examples: "LET a = 1", or simply "a = 1"
- A variable is explicitly declared via a DIM statement (or via the synonymous VAR statement)
- examples: "DIM a = 1", "DIM a AS INTEGER", "VAR a = 1", "VAR a AS INTEGER"
Variables declared in the main part of the program are available to all parts of a program (i.e. the "main" part, every subroutine, and every function.) However, if a subroutine/function declares a local variable with the same name as a variable at the global variable, that subroutine/function no longer has access to that global variable. (BAM has no way of "qualifying" a variable name, so there is no way to tell a subroutine/function that a reference to a variable is for the global one versus the local one.)
Variables declared in a subroutine / function (again, whether explicitly or implicitly) are "local" variables. Those variables only exist in, and are only available to, the subroutine/function in which they are declared.
However, if the main program declares (explicitly or implicitly) a variable with the same name as the subroutine, then a subroutine / function must explicitly declare a variable with the same name for the subroutine / function to have a distinct local variable.
Implicit variable declarations in a subroutine/function cause problems:
In a subroutine/function, do make it a practice to always explicitly declare variables with a "DIM" (or with the synonymous keyword "VAR"). It is a very good practice:
Just for the giggles, notice how a subroutine/function can reference a global variable before declaring a local variable with the same name.
Modern programming languages have built-in mechanisms to handle the task. For example, in QB64 Phoenix Edition, all globally declared variables are private (only available to the main program) unless they are explicitly declared as available to subroutines/functions via the "SHARED" keyword used in a "DIM" statement (click on the keywords to view related documentation in the QB64pe wiki).