A subroutine is a block of code which may be called at any time from a program. This code may need to be executed multiple times, and subroutines provide an invaluable means to simplify code by replacing these blocks of code with a single subroutine call. A subroutine also serves to allow a user to extend the FreeBASIC language to provide custom commands. Many of the functions built into FreeBASIC are merely subroutines part of a "runtime library" linked to by default.
The
Sub keyword marks the beginning of a subroutine, and its end is marked by
End Sub. The "name" parameter is the name by which this subroutine is called. For instance, if the declaration is "
Sub...End Sub", the user can execute the code in between "
Sub foo" and "
End Sub" by using "
foo" as a statement. This code is executed separate from the code which calls the subroutine, so any variable names, unless they are shared, are not available to the subroutine. Values can, however, be passed using parameters.
Parameters are the arguments passed to any statement. For instance, if a user executes a statement as "
Print 4", the value "4" is passed to the function "
Print". Parameters that need to be passed to a subroutine are supplied by one or more parameter arguments in the "
Sub" keyword. Creating a subroutine with "
Sub mysub(foo, bar)...End Sub", allows the code in between "
Sub" and "
End Sub" to refer to the first passed argument as "foo" and the second passed argument as "bar". If a parameter is given a default value, that parameter is optional.
Parameters must also have a supplied type, in the form "
parameter as type". If this is omitted,
type is assumed to be
Integer. A passed value MUST be of the type specified.
A subroutine can also specify how parameters are passed, either as "
ByRef" or "
ByVal", as shown in the syntax definition. If a parameter is "
ByRef", the parameter name literally becomes a reference to the original variable passed to the subroutine. Any changes made to that variable will be reflected outside of the subroutine. If a parameter is passed "
ByVal", however, the value of any passed variable is copied into a new variable, and any changes made to it will not affect the original. (Note: this does not currently apply to
Strings, and "
ByVal" should be avoided with them for the time being.)
The
Static specifier indicates that the values of all local variables defined in the sub should be preserved between calls. To specify individual local variables as static see the
Static keyword.
Sub is the same as
Function, except it does not allow a value to be returned.
The second syntax defines either a constructor or destructor using the
Constructor and
Destructor keywords, respectively. Constructor subroutines are executed before the first line of code in the module, while destructors execute on module exit. Note the public access specifier and empty parameter list for both constructors and destructors.