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.

158<br />

Defining the Scope of a Variable<br />

Program<br />

File 1 File 2<br />

Figure 2-7:<br />

Subprogram<br />

variables<br />

restrict<br />

access only<br />

to code<br />

stored in<br />

that<br />

particular<br />

subprogram.<br />

X : integer<br />

Y : string<br />

File 3 File 4<br />

Passing data among subprograms<br />

If one subprogram needs to use data stored in another subprogram, what’s<br />

the solution? The easiest (and most dangerous) solution is to let multiple<br />

subprograms access that variable as a global or module variable.<br />

The better solution is to isolate that variable as a subprogram variable and<br />

then share or pass that data to another subprogram. This means you have to<br />

declare two subprograms variables, one in each subprogram. Although cumbersome<br />

(now you know why programs create global or module variables<br />

instead), passing data from one variable to another, dubbed parameter passing,<br />

helps keeps the data isolated in only the subprograms that actually need<br />

to use that data, as shown in Figure 2-8.

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

Saved successfully!

Ooh no, something went wrong!