Skip to content

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 Sub

Constructor/Destructor form:

[Public] Sub identifier [CDecl|Pascal|StdCall] [Overload] [Alias "external_identifier"] [()] [Constructor|Destructor] [Static]

    statements ...
    [Return] ...

End Sub

Parameters

  • identifier — The name of the subroutine.
  • external_identifier — Externally visible (to the linker) name enclosed in quotes.
  • parameter_listparameter[, 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_value can be a literal, a constant, or a shared variable.

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

vb
' 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" )
vb
' The following demonstrates optional parameters.
Sub TestSub(P As String = "Default")
    Print P
End Sub

TestSub "Testing:"
TestSub

Dialect Differences

  • The -lang qb and -lang fblite dialects keep the QB convention: parameters are ByRef by default.
  • In the -lang fb dialect, numeric parameters are passed ByVal by default. Strings and UDTs are passed ByRef by default.

Differences from QB

  • Public and Private access specifiers are new to FreeBASIC.
  • Constructor subroutines are new to FreeBASIC.

See Also

Translated from FreeBASIC official docs. Contact us for removal if infringed.
FreeBASIC is an open-source project, not affiliated with Microsoft