Variable Scope

All variables used inside a SUB or FUNCTION are local by default.  This means that any Sub or Function which is called by another Sub or Function will not see the values of the caller’s local variables, even if the called Sub or Function has variables with the same name.  Local variables are stored on the stack, so when a Sub or Function ends, the memory allocated for all local variables is released.

You can share variables between all of the Subs and Functions by using the GLOBAL keyword in your code.  In the following example, the Message variable is shared by all Subs.  Hello calls Init to initialize the Message variable with the word "Hello!" and then Display to show it.  It then assigns the value "Goodbye!" to Message and again calls Display to show it.  Because Caption is defined as local to Init, it is never seen by the Display Sub:

SUB Init()

  GLOBAL Message AS STRING   ' Declare Message as global

  LOCAL  Caption AS STRING   ' Declare Caption as local

  Caption = "GLOBAL Test"

  Message = "Hello!"

END SUB

 

SUB Display()

  #IF %DEF(%PB_CC)

    PRINT Caption$, Message$

  #ELSE

    MSGBOX Message$,,Caption$

  #ENDIF

END SUB

 

FUNCTION PBMAIN() AS LONG

  CALL Init

  CALL Display

  Message = "Goodbye!"

  CALL Display

END FUNCTION

Global variables retain their value after a Sub or Function ends.

All Subs and Functions see global variables in your code, but external DLLs or executables do not see them.  In order to use a variable from another DLL or EXE it must be passed as a parameter.

It is also possible to create variables that are local to a Sub or Function, but do not lose their value when the Sub/Function ends.  These variables are called Static, and the STATIC keyword is used to create them.  In the following example the Function AddTwo is called 5 times and the result is returned to the caller:

DECLARE FUNCTION AddTwo%()

 

FUNCTION PBMAIN() AS LONG

  LOCAL z%

  FOR z% = 1 TO 5

    #IF %DEF(%PB_CC32)

      PRINT AddTwo%

    #ELSE

      MSGBOX STR$(AddTwo%)

    #ENDIF

  NEXT z%

END FUNCTION

 

FUNCTION AddTwo%()

  STATIC Result%

  Result% = Result% + 2

  FUNCTION = Result%

END FUNCTION

When AddTwo is first called, Result% has a value of zero and it returns a value of two.  Each time it is called thereafter, the old value is incremented by two.  The final result is 10, which is passed back to the caller.

 

See Also

Variables

Default Variable Typing

THREADED variables

LOCAL, GLOBAL and STATIC considerations