Simple: Difference between Function & Sub

This should be a very simple Question. Just wanted to clarify things.

What exactly is the difference between a Sub and a Function?
(besides that a Function can return a value)

For example, if there is this section of processing code that I use often and it doesn't return a value. Under what circumstances should I use a Sub and when a Function?
ShakAsked:
Who is Participating?
 
caraf_gCommented:
There is absolutely NO difference between a Sub and a Function other than the ability to return a value.

There is no reason to dictate the use of either a Sub or a Function; anything you can do with a Function you can achieve by adding an extra parameter (ByRef) to a Sub which is otherwise identical to the Function.

It is purely a question of coding standards prevailing in your working environment; just make sure you write something that "fits in" with the way your other colleagues write their code.
0
 
a111a111a111Commented:
from: http://www.vbonline.com/vb-mag/9807/item/q&A.htm

Public Sub AddAnObject(oAnything As Object)
     mycollection.Add oAnything
     End Sub

     The difference between a function and a sub is that if you don't need to return a value you should use a Sub while if you do, use a function. For example:

     Public Function AddAnObject(oAnything As Object) As Long
     mycollection.Add oAnything
     AddAnObject=mycollection.count
     End Function

http://www.btrust.com/services/training/VB/VBConstTypeProc.htm
0
 
a111a111a111Commented:
Also If you want a free book: Platinum Edition Using Visual Basic 5

http://sflow.chem.wvu.edu/sergei/Vb5Platinum/Default.htm

look at: http://sflow.chem.wvu.edu/sergei/Vb5Platinum/ch17/ch17.htm
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
a111a111a111Commented:
You can use the free book:
http://www.mcp.com/cgi-bin/mcp/mcpsecretary.cgi?

A Function Review


Concept: Functions accept one or more arguments and do work with those arguments. The function then returns a single value.

When you use a function inside a Visual Basic statement, it is said that you're calling a function. For example, the following statement calls the Val()
function:


Num = Val(txtAmt.Text) ' Convert entry to number



          Definition: An argument is a value that you pass to a function.


The parentheses after a function name hold one or more arguments. In the preceding statement, txtAmt.Text is the argument. Some functions, such
as Val(), accept only one argument. Some functions accept more than one argument. Some functions don't require any arguments, and for those
functions, the parentheses are optional. The arguments inside the parentheses are often called the argument list. A function can require none, one, or
several arguments.

When you specify function arguments, you are passing the arguments to the function. The function works on the argument values that you pass to
the function and produces some sort of value from the arguments. As Figure 13.1 illustrates, you send a function one or more arguments and the
function, after using the arguments in the argument list, is said to return a value. That value is the answer to the function, more commonly called the
return value. Functions are said to receive arguments and return a value.
0
 
vikiingCommented:
There's a subtle, but very important, difference: all variables used into a Function are treated as GLOBAL; whereas in a Sub, they're treated as LOCAL.

To override those conditions, you must declare as Private (in a function) or Public (in a Sub) all variables you need.

Look at this:

Dim B as Single
B=9             'Initialize B to any value
x = Func(1)     'Call function
Print B         'Show B
Call Subr(1)    'then call Sub
Print B         'Show B again

Function Func(x)
B=-1
End Function

Sub Subr(x)
B=-2
End Sub


When "Print B" is executed, the value it shows is -1. Although it was initialized with 9, execution of Func() changed its value to -1, because variable B, into Func(), is treated as a global one, thus affecting the B declared at main program.

On the other hand, the second Print will keep on showing B as -1 and not as -2; that's due to the fact that, during Subr execution, it set B=-2, yes, but that B is local to procedure and belongs only to it; therefore, the value of B (belonging to main program) is not altered.

0
 
ShakAuthor Commented:
Thanks for replying.

a111, you are right in saying that functions return a value. But I'm already aware of that and I did mention it in the question. I was wondering if there were other differences between a function and a sub.

vikiing, thanks for your response too, but I don't think you are right. What you said is more related to "ByRef" and "ByVal" in the declaration of the sub/function, rather than related to the difference between function and sub.

Perhaps there is NO other difference other than the ability to return a value, but then again, perhaps there is. Hope someone can enlighten me.

Thanks again.

0
 
vikiingCommented:
Friend Shak: you've said "I don't think you are right. What you said is more related to "ByRef" and "ByVal" in the declaration of the sub/function, rather than related to the difference between function and sub".

Well, Shak; this is not a matter of "I think" or "I don't think"; please, type out and execute the little code I've posted and you'll see the difference. Please, also notice my code does nothing about arguments; thus, there's nothing about the way they're passed (by value or by reference). In fact, the example I've posted could perfectly had no arguments at all.

Caraf_G said: "There is absolutely NO difference between a Sub and a Function other than the ability to return a value". As I've mentioned before, and anybody can prove it, THERE IS a difference; of course, that difference is not functional (regarding the ability of doing something), but only in the way global and local variables are treated.

Unless stated otherwise, a Function can alter main-program's variables, whereas a Sub can not; a subtle (but heavy !!) fact which can makes the difference between a program works and another doesn't.
0
 
caraf_gCommented:
vikiing

A Function can alter main-program's variables. Correct.

So can a Sub

As long as these variables have been declared as Public or Global in a standard VB module

Sorry mate, but like I said, there is NO difference between a Function and a Sub in the sense that you are implying.

0
 
caraf_gCommented:
Just to show you

Tried the following in a VB Form module

Dim B As Single

Private Sub Command1_Click()

B = 9 'Initialize B to any value
x = Func(1) 'Call function
Print B 'Show B
Call Subr(1) 'then call Sub
Print B 'Show B again

End Sub

Function Func(x)
B = -1
End Function

Sub Subr(x)
B = -2
End Sub

This printed -1, followed by -2 as I would expect

Then localised B to the Command Button's Click method:

Private Sub Command1_Click()

Dim B As Single
B = 9 'Initialize B to any value
x = Func(1) 'Call function
Print B 'Show B
Call Subr(1) 'then call Sub
Print B 'Show B again

End Sub

Function Func(x)
B = -1
End Function

Sub Subr(x)
B = -2
End Sub

This time it printed the value 9 twice, again as expected.

Actually, the code sample you've written is impossible in VB unless the code calling the sub and function is part of another sub or function..... In actual fact, the Print statements are not valid without a suitable object (such as a form) so you couldn't even write this code in a VB program without any forms (in its Sub Main) - In VB5 at least

Are you using VB or QBASIC?

0
 
ShakAuthor Commented:
Errmm.... I smell animosity.

Cool it guys.

vikiing, well, I did try your code, and it doesn't work like you said. And as for ByRef and ByVal, I had thought you made a mistake in the declaration or something. Usually, the way to control whether a value passed into a function/sub can be modified, is to use ByRef/ByVal.

caraf, thanks for your answer. But you're not quite right on the print part though. If you leave out the object, VB would use the form to print.

So probably I've been right in thinking that's the only difference. (and I sure hope that is RIGHT).

Thanks guys.

p/s vikiing, it would be interesting to know how you managed to get your results though. If you could reproduce it, perhaps could you cut/paste the code again?
0
 
caraf_gCommented:
Hello Shak,

Sorry about that - no animosity intended... just a "heated argument".

The comment about the "print" was to do with VB projects that don't have any forms at all - in that case, you will need at least one normal VB module in which you declare a Sub Main which runs as the startup module for your .exe

If you do that, there is no object defined for the "print" command to relate to and you'll get an error message saying "statement not valid without a suitable object".

When you use "print" within a Form module VB will automatically assume that since you didn't specify an object you must intend to print to the current form and hence you don't get that problem.

PS - I have since tried to reproduce vikiing's predicted results in QBASIC and have still not been able to do so. I'm really intrigued now as to what version of what product vikiing might be using to get the reported results.
0
 
vikiingCommented:
Dear friends: I must apologize for the mess. VB makes no difference about local and global variables, regarding func and sub. I was wrong, and I'm sorry for being so stupidly cathegoric.

I've worked during many years with Turbo Basic (Borland's), where things really are as I said. I don't know why I had the idea VB followed the same rules (in fact, I've written that piece of code even without having executed it, as I was so absolutely, and blindly, sure of that).

The only way to achieve what I said is this:

Dim b As Single
Private Sub Form_Load()
b = 9 : Print b
x = func : Print b
Call subr : Print b
End Sub

Function func()
b = -1
End Function

Sub subr()
Dim b As Single
b = -2
End Sub

In this way, Subr declares B as local to itself, because, by default (without that statement) B is global, not local, as I've wrongly sustained.


Once again, please, accept my apologize for my stupidness.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.