30.07.2013 Views

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 7 Arrays 263<br />

84 element *= 2<br />

85 output &= vbCrLf & "Value calculated in " & _<br />

86 "ModifyElementByRef: " & element<br />

87 End Sub ' ModifyElementByRef<br />

88<br />

89 End Module ' modPassArray<br />

Fig. Fig. 7.8 7.8 Passing arrays and individual array elements <strong>to</strong> procedures (part 3 of 3).<br />

The For/Next structure on lines 18–20 appends the five elements of integer array<br />

array1 (line 10) <strong>to</strong> String output. Line 22 passes array1 <strong>to</strong> procedure ModifyArray<br />

(line 58), which then multiplies each element by 2 (line 62). To illustrate that<br />

array1’s elements were modified in the called procedure (i.e., as enabled by passing by<br />

reference), the For/Next structure in lines 28–30 appends the five elements of array1<br />

<strong>to</strong> output. As the screen capture indicates, the elements of array1 are indeed modified<br />

by ModifyArray.<br />

To show the value of array1(3) before the call <strong>to</strong> ModifyElementByVal, lines<br />

32–35 append the value of array1(3) <strong>to</strong> String output. Line 38 invokes procedure<br />

ModifyElementByVal and passes array1(3). When array1(3) is passed by<br />

value, the Integer value in the fourth position of array array1 (now an 8) is copied<br />

and is passed <strong>to</strong> procedure ModifyElementByVal, where it becomes the value of argument<br />

element. Procedure ModifyElementByVal then multiplies element by 2<br />

(line 73). The parameter of ModifyElementByVal is a local variable that is destroyed<br />

when the procedure terminates. Thus, when control is returned <strong>to</strong> Main, the unmodified<br />

value of array1(3) is appended <strong>to</strong> the string variable output (lines 40–41).<br />

Lines 43–51 demonstrate the effects of procedure ModifyElementByRef (lines<br />

80–87). This procedure performs the same calculation as ModifyElementByVal, multiplying<br />

element by 2. In this case, array1(3) is passed by reference, meaning the<br />

value of array1(3) appended <strong>to</strong> output (lines 50–51) is the same as the value calculated<br />

in the procedure.<br />

Common <strong>Program</strong>ming Error 7.3<br />

In the passing of an array <strong>to</strong> a procedure, including an empty pair of parentheses after the<br />

array name is a syntax error. 7.3

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

Saved successfully!

Ooh no, something went wrong!