Functions and Subs

dannyres

Regular
Joined
Aug 29, 2003
Messages
67
Hi guys, ive been working on a project latly (im a n00b to .net) and im wondering.. what is the difference between a function and a sub... from what i can tell, a function is something that gets something and returns a value, and a sub is what does something.. could someone explain to me what is what and when to use each one?


Thanks, Dan
 
Pretty much the only difference between the two is that a function returns a value. The last line of a function tells what value it will return, like this:

Visual Basic:
Return WhateverValueYouWant
Since a function returns a value, you will call it on the right side of an equals sign. That way you can assign the return value of the function to a variable. A sub procedure, however, is called by itself on its own line of code. It doesn't return a value, but just executes the code inside of it.

I hope this helps.
 
You also usually declare a Function as a specific data type and Functions are normally passed some data or value to use in its process.
Visual Basic:
Public Function MyFunction(ByVal i As Integer, ByVal x As Long) As Long
     Dim n As Long
     'Some code here to do something...
     n = x * i
     Return n
End Function
Subs aren't type specific and don't always have data passed to them, although they can recieve some kind of data as a parameter. I like the way that the C languages deal with routines. ALL routines in the C's have a return type. If the routine is not required to return a value it is "void", other wise there is a data type associated with it. But, I digress. I know it's a lot more than you were asking but, for some reason I'm feeling long-winded tonight! Hope I did help a little.
 
Ok i think ive got it now :)


Thanks, Dan

EDIT: is it bad coding practice to have a function that doesnt return anything?
 
Back
Top