What is the difference between a function and a subroutine??
Printable View
What is the difference between a function and a subroutine??
A subroutine is any callable code... what makes one a function vs not, is if it returns a value. Functions are intended to return a value.
-tg
A Sub routine basically sits on the couch eating sandwiches watching football games, where as Functions make sandwiches for the Sub.
Code:Private Sub HoneyMakeMeASandwhich()
Dim MySandwhich As String = MakeSandwhich("PB&J")
End Sub
Private Function MakeSandwhich(ByVal Type As String) As String
If Type = "PB&J" Then
Return "We sont have jelly!"
Else
Return "Make your own damn sandwhich!"
End If
End Function
It's a fun conversation, as hinted by so many people responding. I like to talk all computer sciencey.
Mathematically, a function is a formal definition of a thing that takes inputs and produces outputs. f(x) = x + 3 is a mathematical function. The name is "f of x", because mathemeticians have even fewer keystrokes to waste than programmers and don't like to use descriptive names for things. In English, that would read:
So if I say "f(7)", I mean "10", because if 7 is x, and f(x) is x + 3, then f(7) = 7 + 3 = 10. Math.Quote:
f of x is a function that returns the result of adding three to x.
Many programming languages call EVERYTHING functions because programming languages are based on math, and in math a function MUST return a value. Even if you write something goofy like f(x) = 7, that function returns 7. You can't write a function that returns nothing in math. It's impossible.
But in terms of what we do in programming, sometimes we want to "call something" without getting a value back. For example, closing a Window isn't an operation for which there is any sensible return value. So programming languages have to deviate from math in this respect. In a programming language, we can say f(x). That would mean "f of x is a function that returns no value".
C-style languages express this via the return type void. VB expresses this via the Sub/Function distinction. In VB:
- A Function is "a thing you can call that also returns a value".
- A Sub is "a thing you can call that does not return a value".
Functions and subroutines are called in the same way. The only difference between functions and subroutines is that functions must return data, whereas subroutines need not. Functions and Subroutines are lines of code that you use more than once. The purpose of functions and subroutines is to save time and space by just calling a function/subroutine. There is hardly a difference between the two, except that a function returns a value, where a subroutine just repeats lines of code