What is the difference between a function and a sub ?
Printable View
What is the difference between a function and a sub ?
a function returns a value, a sub normally does not.. is that good enough ?
In which circumstance should I use a function and when should I use a sub?
I think a function performs a task, and then always returns a value. Also with a function, it must be passed some arguments. A sub does not have either of these two requirements. A sub can either be called (without being passed any arguments) or triggered on an event (such as a mouse click).
This is by no means a computer science definition, more just an observation of mine.
sort of relevant:
http://www.vbforums.com/showthread.p...nction+AND+sub
very good thread:
http://www.vbforums.com/showthread.p...nction+AND+sub
A function doesn't have to have any arguments passed to it:Quote:
Originally posted by Darren
Also with a function, it must be passed some arguments.
VB Code:
Public Function Testing() As Single 'no arguments in the () Dim fResult As Single fResult = Rnd Testing = fResult End Function Private Sub CommandCallFunction_Click() TextHello = Testing ' no argument End Sub
Just to confuse the matter ever more... you are perfectly allowed to create a function and never assign the return value... Now, you can really confuse the heell out of people reading your code.
Is that messed-up or what ?
A VB function will always return a value.Quote:
Originally posted by FrancisC
Just to confuse the matter ever more... you are perfectly allowed to create a function and never assign the return value... Now, you can really confuse the heell out of people reading your code.
Is that messed-up or what ?
If you haven't explicitly told what to return a default value will be sent back to the caller.
The default values are zero for numeric data types, and empty string for strings and False for boolean return values.
Best regards