15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

156<br />

Defining the Scope of a Variable<br />

else on there instead. Would you feel safe leaving your wallet and laptop on<br />

such a shelf? If not, you probably wouldn’t feel safe putting your data in a<br />

global variable either.<br />

Because global variables can be so dangerous, most <strong>programming</strong> languages<br />

don’t let you create a global variable unless you specifically tell the computer<br />

to create one. To create a global variable, you often have to use a special<br />

keyword, such as global or public, such as<br />

Global X : Integer<br />

The preceding command tells the computer to create a global variable,<br />

called X, that can hold an integer data type. You type a global variable<br />

declaration in any file that contains your main program or a library of<br />

subprograms.<br />

Restricting scope to a module<br />

A module is another term <strong>for</strong> a separate file. If you divide a large program<br />

into subprograms and store those subprograms in a separate file, each file is<br />

a module. A module variable lets you create a variable that can be accessed<br />

only by code stored in that particular module, as shown in Figure 2-6.<br />

The advantage of module variables is that they give you the convenience of<br />

a global variable but without the danger of letting every part of a program<br />

access that variable. Instead, module scope limits access only to code in<br />

that file.<br />

Although an improvement over global variables, module variables also have<br />

some of the disadvantages of global variables. If a file contains a lot of subprograms,<br />

trying to find which line of code is messing up your module variable<br />

can still be troublesome.<br />

To create a module variable, you generally just declare a variable at the top<br />

of any file except you don’t use the Global or Public keyword. In some<br />

<strong>programming</strong> languages, you declare a module variable with the Private<br />

keyword, such as<br />

Private X : integer;<br />

The preceding code would declare a module variable called X, which can<br />

hold an integer data type.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!