05-21-2025, 09:45 AM
(05-21-2025, 09:12 AM)bplus Wrote: To illustrate further the difference between a Function and an equivalent Sub:
Code: (Select All)nNames = 5
Dim names$(1 To nNames)
names$(1) = "PhilOfPerth"
names$(2) = "bplus"
names$(3) = "ahenry3068"
names$(4) = "SMcNeill"
names$(5) = "Who am I?"
For i = 1 To nNames
' using a function only takes one line to report results
Print "Function last letter for "; names$(i); " is "; LastLetter$(names$(i))
' using a sub like a Function usually requires a call to it then another line to report results
lastLetter names$(i), ll$
Print "Sub last letter for "; names$(i); " is "; ll$
Next
Function LastLetter$ (mystring$)
LastLetter$ = Mid$(mystring$, Len(mystring$), 1)
End Function
Sub lastLetter (mystring$, myLastLetter$)
myLastLetter$ = Mid$(mystring$, Len(mystring$), 1)
End Sub
Phil: "With a Sub I can change several variables at the same time."
If you need variables changed then yeah by all means use a Sub.
Functions do a job of processing some information and returning a single result like a formula Area = Pi*R^2
Function AreaCircle(R)
AreaCircle = _Pi * R^2
End Function
The advantage of Functions is they wont change their arguments unless you tell them to.
Note that this is... wrong? Misleading at the very least.
Functions behave *exactly* as Subs do with regards to passing values and changing their arguments. I'm not certain what "unless you tell them to" refers to, but if types match and values change inside the function, they'll change outside it too.
x = 1
PRINT foo (x)
PRINT foo (x)
PRINT x
FUNCTION foo (x)
foo = 2 * x
X = x + 1
END FUNCTION
^ Prints 2 (x = 1), then 4 (x = 2 after the first call), then 3 (final value of x)