Personal tools
You are here: Home VariableScope
FrontPage >> MapInfoRoadmap >> MapBasicDevelopment >> NamingVariables >>

VariableScope

Document Actions
last edited 2 years ago by WikiWillie

The scope of a variable refers to the span of code in which a variable can be "seen." In MapBasic, when you declare a variable in a subroutine or a function using the Dim statement, then that variable can be read or written to only by code in that subroutine or function. The variable is said to have "local scope." This means that the variable exists only while the subroutine or function in which it is declared is executing.

However if you declare it outside of any subroutine or function, then that variable can be read and modified by any subsequent code in the module (a module is the whole *.mb file.) For example, suppose you have the following code:

Declare Sub Main
Declare Sub DateStamp

Dim sText As String Sub Main sText = "Today is " Call DateStamp Print sText End Sub Sub DateStamp sText = sText & CurDate() End Sub

By declaring sText above all the subroutines, you extend the scope of sText to the entire module, allowing all subroutines to read and write this variable. You could also use the Global declaration instead of Dim, like so:
Global sText As String
In a single module, there is no effective difference between Dim used outside subroutines and Global (which can only be used outside subroutines) but if you are linking more than one module together then the Global declaration allows you to expand the variable's scope to all modules in which the variable is declared as "Global".

Generally speaking, it is better programming practice to limit the scope of variables as much as possible. If you want a subroutine to have access to a variable, it is better to pass it as a parameter then to give it global scope. The reason is that if a variable is global, it's hard to spot all the places where it might be changed by a subroutine or a function, and therefore the code is more prone to subtle bugs and is harder to maintain.

But if used in a well-controlled manner, and clearly identified using an intelligent convention for NamingVariables, variables with broader scope can be very useful.

« December 2008 »
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
 

Powered by Plone, the Open Source Content Management System

This site conforms to the following standards: