SUB
Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgSub Last revised: 2023-08-30
Defines a procedure (subroutine).
Syntax
[Public|Private] Sub identifier [CDecl|Pascal|StdCall] [Overload] [Alias "external_identifier"] [( [parameter_list] )] [Static] [Export]
statements ...
[Return] ...
End SubConstructor/Destructor form:
[Public] Sub identifier [CDecl|Pascal|StdCall] [Overload] [Alias "external_identifier"] [()] [Constructor|Destructor] [Static]
statements ...
[Return] ...
End SubParameters
- identifier — The name of the subroutine.
- external_identifier — Externally visible (to the linker) name enclosed in quotes.
- parameter_list —
parameter[, parameter[, ...]]- parameter:
[ByRef|ByVal] identifier [As type] [= default_value]- If the argument is an array, the identifier must be followed by an empty parenthesis
(). default_valuecan be a literal, a constant, or a shared variable.
- If the argument is an array, the identifier must be followed by an empty parenthesis
- parameter:
Description
A subroutine is a block of code which may be called at any time from a program. The Sub keyword marks the beginning of a subroutine, and its end is marked by End Sub.
Variables are local to the sub unless they are shared. Values can be passed using parameters. If a parameter is given a default value, that parameter is optional.
Array parameters are always ByRef; the ByRef keyword is neither required nor allowed for array parameters.
In the default dialect -lang fb, parameters must have a supplied type (As type). In -lang qb and -lang fblite, a default type is assumed if not given.
The Static specifier indicates that the values of all local variables defined in the sub should be preserved between calls.
Constructor subroutines are executed before the first line of code in the module, while destructors execute on module exit.
Examples
' Example of writing colored text using a sub:
Sub PrintColoredText( ByVal colour As Integer, ByRef text As String )
Color colour
Print text
End Sub
PrintColoredText( 1, "blue" )
PrintColoredText( 2, "green" )
PrintColoredText( 4, "red" )' The following demonstrates optional parameters.
Sub TestSub(P As String = "Default")
Print P
End Sub
TestSub "Testing:"
TestSubDialect Differences
- The
-lang qband-lang fblitedialects keep the QB convention: parameters areByRefby default. - In the
-lang fbdialect, numeric parameters are passedByValby default. Strings and UDTs are passedByRefby default.
Differences from QB
- Public and Private access specifiers are new to FreeBASIC.
- Constructor subroutines are new to FreeBASIC.