Remember Functions (?)
See also: April 12 lecture, "Procedures -- Abstracting Common Operations"


one way to look at functions

Remember Subs?

"Functions are kind of like Subs..."

Functions, like Subs, are a like mini-programs, i.e. nicely packaged and named sequences of statements (instructions)

"...'cept different."

Functions, unlike Subs, have an answer to return to the caller once they're done running, so...

One common use of functions is for computing formulas or common mathematical operations, e.g.

...conversion of Fahrenheit degrees to Celsius degrees<
...given the month (as a number), the number of days in it

...the square root of a number
...the average of a set of numbers (Sound familiar?)
...the largest or smallest of a set of numbers

parameters and the return value

Functions often take parameters, basically like input for a program.

The "answer" that the function computes is called the return value.

anatomy of a function definition

    Function convertInToCm(inches As Single) As Single
	convertInToCm = inches * 2.54
    End Function

Looks like Sub at first glance, since it's got a parameter list (blue), but notice the type specification (red) at the end. The type of your return value (answer) goes here.

Look more closely (green), and you'll notice something that looks like a variable assignment. But convertInToCm isn't declared as a local variable, so this can't be a variable assignment, really.

It basically looks like an assignment with the function name on the left hand side! It turns out this is how you tell VB what you want the function to return.

How do I use 'em?

Remember this little lesson from the last handout about arrays, little grasshoppers?
There's a similar rule to be learned for calls to functions:
Here's how you might use the function convertInToCm in a Sub (or another function):
    Dim heightInInches As Single
    Dim converted As Single
    
    heightInInches = 5 * 12 + 10
    converted = convertInToCm(heightInInches)

    ...

note: Unlike Subs, when you call (use) a function, you don't use the Call keyword.

another note: Unlike array elements and variables, you cannot put function calls on the left hand side of assignments. (Think about whether this would make sense anyhow, eh?)

function vocabulary

*including none at all, just like Subs




Ken Yasuhara <yasuhara@cs.washington.edu>
Last modified: Tue May 11 11:51:31 PDT 1999