15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

154<br />

Defining the Scope of a Variable<br />

Now if the sales tax changes from 0.075 to 0.080, you just need to change this<br />

value in one constant declaration, such as<br />

Const sales_tax as Single = 0.080<br />

This one change effectively plugs in the value of 0.080 everywhere your program<br />

uses the sales_tax constant. So constants offer two advantages:<br />

✦ They let you replace fixed values with descriptive constant names.<br />

✦ They let you change the value of a constant once and have those<br />

changes occur automatically in the rest of your program.<br />

So use constants to replace fixed values and use variables to store different<br />

types of data retrieved from the outside world. Every program needs<br />

to use variables, but not every program needs to use constants.<br />

After you understand how to store data temporarily in variables, your program<br />

can start manipulating that data to do something useful.<br />

Defining the Scope of a Variable<br />

The scope of a variable defines which part of your program can store and<br />

retrieve data in a variable. Because variables store data that your program<br />

needs to work correctly, your program must make sure that no other part of<br />

the program accidentally modifies that data.<br />

If your program stores a person’s credit card number in a variable, you don’t<br />

want another part of your program to accidentally retrieve that data and<br />

change the numbers around or send a hundred copies of each credit card<br />

number to customers outside the company.<br />

So when creating variables, limit the variables’ scope. The scope simply<br />

defines which parts of your program can access a variable. When you<br />

declare a variable, you also define one of three possible scope levels <strong>for</strong> that<br />

variable:<br />

✦ Global<br />

✦ Module<br />

✦ Subprogram<br />

Handling global variables with care<br />

In a global variable, any part of your program can access that variable,<br />

including storing new data in that variable (and wiping out any existing data<br />

already stored in that variable), changing the data in a variable, or wiping<br />

out the data in a variable altogether, as shown in Figure 2-5.

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

Saved successfully!

Ooh no, something went wrong!