By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,639 Members | 2,262 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,639 IT Pros & Developers. It's quick & easy.

Sub vs function

P: n/a
What's the difference between a Sub and a Function?

Nov 21 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

A Function can return a value from itself. For example

Public Function Sum(ByVal a As Integer, _
ByVal b As Integer) As Integer
Return a + b
End Function

Then you can use this Function as follows

Dim result As Integer = Sum(2, 4)

On the other hand a Sub can not return a value from itself. It must use a
ByRef parameter to get a result. For example

Public Sub SumSub(ByVal a As Integer, _
ByVal b As Integer) As Integer)
Dim theSum As Integer = a + b
End Sub

This has no way of returning the result and using this like

Dim answer As Integer = SumSub(2, 4)

will generate a complile time error.

We can alter SumSub to take a ByRef parameter.
Public Sub SumSubByRef(ByVal a As Integer, _
ByVal b As Integer) As Integer, ByRef theSum As Integer)
theSum = a + b
End Sub

Then we can do the following

Dim answer As Integer
SumSubByRef(2, 4, answer)

This will get the sum placed into the variable answer.

As you can see, if you are going to be returning a value from your procedure
it is better to write it as a Function rather than a Sub.

Robby

"David A. Osborn" <do********@hotmail.com> wrote in message
news:KkoBd.1250$wu4.424@attbi_s52...
What's the difference between a Sub and a Function?

Nov 21 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.