7.4. Functions: Methods That Return a ValueFunctions (known as Function procedures in earlier versions of Visual Basic) are methods that return a value to the caller (whereas subroutines do not). The console application in Fig. 7.2 uses the function Square to calculate the squares of the integers from 110. Figure 7.2. Function for squaring an integer.
The For...Next statement (lines 810) displays the results of squaring the integers from 110. Each iteration of the loop calculates and displays the square of control variable counter (line 9). Function Square is invoked (line 9) with the expression Square(counter). When program control reaches this expression, the program calls Square (lines 1416). At this point, the program makes a copy of the value of counter (the argument), and program control transfers to the first line of Square. Square receives the copy of counter's value and stores it in the parameter y. Line 15 is a Return statement, which terminates execution of the method and returns the result of y ^ 2 to the calling program. The result is returned to the point in line 9 where Square was invoked. Line 9 displays in the command prompt the value of counter and the value returned by Square. This process is repeated 10 times. Note that returning a value from a function is similar to returning a value from the Get accessor of a property. Function DeclarationsThe format of a function declaration is
The method-name, parameter-list, and declarations and statements in a function declaration behave like the corresponding elements in a subroutine declaration. In the function header, the return-type indicates the type of the result returned from the function to its caller. The statement
can occur anywhere in a function body and returns the value of expression to the caller. If necessary, Visual Basic attempts to convert the expression to the function's return-type. Functions Return exactly one value. When a Return statement is executed, control returns immediately to the point at which that function was invoked. Common Programming Error 7.2
Common Programming Error 7.3
|