3.2 Subroutine versus Function

In short (and I mean short), the different is that a subroutine does not return a value, whereas a function does.

The ability to return a value means that a subroutine can specify a value that can be used immediately in an expression. This feature makes it convenient to utilize processed information from a subroutine.

1Function Sum(ByVal x As Integer, ByVal y As Integer
2  Sum = x + y 
3End Function

This may seem like a silly little subroutine, but it helps to illustrate a few important points.

First, it is marked as a Function instead of a Sub. This means that the subroutine can return a value. Second, note that assignment statement uses Sum itself as the left hand side. However, in this case, Sum does not refer to a variable, it refers the function itself. The assignment statement specifies the return value of the subroutine.

We will also discuss the word ByVal later. For now, let us see how this function can be used.

Let us consider the following statement:

counter = counter + 1

This is hardly any mystery, it increments the counter by one. Now that we have Sum defined, we can use it instead:

counter = Sum(counter, 1)  
    

In this case, counter specifies x, and 1 specifies y. The return value of x+y is an integer that can be used directly anywhere an integer value can go. In this case, the right hand side of an assignment.

Let us consider another statement:

sumOf3 = p + q + r  
    

This statement can now be done using Sum as follows:

sumOf3 = Sum(Sum(p, q), r)  
    

This means that the result of a function can be utilized as the parameter of another function.