Getting Started
Introduction
Sample Programs
QBasic IDEs
History
Advice
Tools
Mini-Tutorial
Tutorial
Code Snippets

Resources
Web Sites
More Tutorials
Vendors
Books
Magazines
NewsLetters
NewsGroups
Forums
User Groups
Talk Shows
Blogs

GBIC >> QBasic >> Tutorial >> Scope

QBasic Information Center Tutorials - Scope
These tutorials were written to help you get a quick, but thorough, understanding of QBasic - the scope of the language as well as it's specific capabilities.

Scope
By default, a variable declared at a module-level (outside procedures) cannot be accessed within a procedure. It is possible to declare a duplicate variable within a procedure which has the same name as the module-level variable, but the module-level value is not carried into the procedure. Also, if the duplicate variable is assigned a value, the assignment does not change the value of the module-level variable.

The following code gives an example of this.

     x$ = 5        # x$ is defined at a module level
     sub mytest    # subroutine 'mytest'
        print x$   # module-level value of x$ is not available here
     end sub

The x$ in the procedure is considered to have "local" scope. Local means it exists only within the procedure where it was declared.

Controlling Scope
However, by using the SHARED operator when creating a variable at the module level, the variable will be available within all procedures, as in the following example:

     SHARED x$    # shares x$ with all procedures
     x$=5         # $x is global, existing in all blocks
     sub mytext   # use of 'my' means $y exists only in this block
        print x$  # x$ is shared, so '5' is printed
     end sub