xHarbour Reference Documentation > Statement Reference |
Declares and optionally initializes a local memory variable.
LOCAL <varName> [:= <xValue> ]
The LOCAL statement declares a lexical memory variable that has LOCAL scope. Local variables are resolved by the compiler, i.e. their symbolic name cannot be retrieved during runtime. This makes access to LOCAL variables much faster than to dynamic memory variables of PRIVATE or PUBLIC scope, whose symbolic variable names exist at runtime.
The names of LOCAL variables cannot be included in macro-expressions since they cannot be resolved by the macro operator (&). This operator requires the symbolic name of a variable to exist at runtime.
The visibility and lifetime of LOCAL variables is restricted to the function, procedure or method that declares a LOCAL variable. Unlike PRIVATE or PUBLIC variables, LOCAL variables cannot be seen in a subroutine. To make the value of a LOCAL variable visible in a subroutine, it must be passed as a parameter to the subroutine.
When a routine executes the RETURN statement, all LOCAL variables declared in that routine are discarded and their values become subject to garbage collection.
The lines in PRG source code preceding the LOCAL statement may not call executable code. They can only contain declaration statements, i.e. only the FUNCTION, METHOD, PROCEDURE statements, and the FIELD, MEMVAR, PARAMETERS, PRIVATE, PUBLIC, STATIC variable declarations are allowed to precede the LOCAL statement.
It is possible to initialize a local variable already in the LOCAL statement. To accomplish this, the inline-assignment operator must be used. The value of any valid expression can be assigned. This includes literal values and the return values of functions.
Note: If a PRIVATE or PUBLIC variable exists that has the same symbolic name as a LOCAL variable, only the LOCAL variable is visible. PRIVATE or PUBLIC variables with the same name become visible again, when the LOCAL variable gets out of scope, i.e. when the routine that declareS the LOCAL variable returns or calls a subroutine.
See also: | FUNCTION, GLOBAL, PARAMETERS, PRIVATE, PROCEDURE, PUBLIC, STATIC |
Category: | Declaration , Statements |
// The example demonstrates the visibility of LOCAL and PRIVATE // memory variables PROCEDURE Main PRIVATE myVar := "Private Var" ? Procname(), myVar Test1() RETURN PROCEDURE Test1 LOCAL myVar := "Local Var" // PRIVATE myVar is unvisible ? Procname(), myVar Test2() RETURN PROCEDURE Test2 // PRIVATE myVar is visible ? Procname(), myVar RETURN
http://www.xHarbour.com