19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

84 <strong>Computer</strong> <strong>Programming</strong> <strong>Concepts</strong> <strong>and</strong> <strong>Visual</strong> <strong>Basic</strong><br />

default value 0, <strong>and</strong> string variables default to the empty string.) The variables in a Sub procedure<br />

are said to be local to the Sub procedure in which they reside.<br />

EXAMPLE 4<br />

The following program illustrates the fact that each time a Sub procedure is called, its variables are set to<br />

their default values; that is, numerical variables are set to 0 <strong>and</strong> string variables are set to the empty string.<br />

Private Sub cmdDisplay_Click()<br />

‘Demonstrate that variables in a Sub procedure do<br />

‘not retain their values in subsequent calls<br />

picResults.Cls<br />

Call Three<br />

Call Three<br />

End Sub<br />

Private Sub Three()<br />

Dim num As Single<br />

‘Display the value of num <strong>and</strong> assign it the value 3<br />

picResults.Print num;<br />

num = 3<br />

End Sub<br />

[Run, <strong>and</strong> then click the comm<strong>and</strong> button. The following is displayed in the picture box.]<br />

0 0<br />

EXAMPLE 5<br />

The following program illustrates the fact that variables are local to the part of the program in which they<br />

reside. The variable x in the event procedure <strong>and</strong> the variable x in the Sub procedure are treated as different<br />

variables. <strong>Visual</strong> <strong>Basic</strong> h<strong>and</strong>les them as if their names were separate, such as xcmdDisplay_Click <strong>and</strong><br />

xTrivial. Also, each time the Sub procedure is called, the value of variable x inside the Sub procedure is<br />

reset to 0.<br />

Private Sub cmdDisplay_Click()<br />

Dim x As Single<br />

‘Demonstrate the local nature of variables<br />

picResults.Cls<br />

x = 2<br />

picResults.Print x;<br />

Call Trivial<br />

picResults.Print x;<br />

Call Trivial<br />

picResults.Print x;<br />

End Sub<br />

Private Sub Trivial()<br />

Dim x As Single<br />

‘Do something trivial<br />

picResults.Print x;<br />

x = 3<br />

picResults.Print x;<br />

End Sub<br />

[Run <strong>and</strong> then click the comm<strong>and</strong> button. The following is displayed in the picture box.]<br />

2 0 3 2 0 3 2

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

Saved successfully!

Ooh no, something went wrong!