Sub
 
Defines a procedure

Syntax

[Public|Private] Sub identifier [cdecl|pascal|stdcall] [Overload] [Alias external_identifier] [( [parameter_list] )] [Static]
statements
...
[Return]
...
End Sub

[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_list: parameter[, parameter[, ...]]
parameter: [ByRef|ByVal] identifier [As type] [= default_value]
identifier: the name of the variable referenced in the subroutine
type: the type of variable
default_value: the value of the argument if none is specified in the call
statements: one or more statements that make up the subroutine body

Description

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.

Example

'' 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" )        '' a few colors
   PrintColoredText( 2, "green" )
   PrintColoredText( 4, "red" )
   Print
   
   Dim i As Integer
   For i = 0 To 15                        '' all 16 colors
      PrintColoredText( i, ("color " & i) )
   Next i

' The following demonstrates optional parameters.

Sub TestSub(P As String = "Default")
    Print P
End Sub

TestSub "Testing:"
TestSub


Dialect Differences

Differences from QB

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

See also

Сайт ПДСНПСР. Если ты патриот России - жми сюда!


Знаете ли Вы, что релятивизм (СТО и ОТО) не является истинной наукой? - Истинная наука обязательно опирается на причинность и законы природы, данные нам в физических явлениях (фактах). В отличие от этого СТО и ОТО построены на аксиоматических постулатах, то есть принципиально недоказуемых догматах, в которые обязаны верить последователи этих учений. То есть релятивизм есть форма религии, культа, раздуваемого политической машиной мифического авторитета Эйнштейна и верных его последователей, возводимых в ранг святых от релятивистской физики. Подробнее читайте в FAQ по эфирной физике.

НОВОСТИ ФОРУМАФорум Рыцари теории эфира
Рыцари теории эфира
 10.11.2021 - 12:37: ПЕРСОНАЛИИ - Personalias -> WHO IS WHO - КТО ЕСТЬ КТО - Карим_Хайдаров.
10.11.2021 - 12:36: СОВЕСТЬ - Conscience -> РАСЧЕЛОВЕЧИВАНИЕ ЧЕЛОВЕКА. КОМУ ЭТО НАДО? - Карим_Хайдаров.
10.11.2021 - 12:36: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от д.м.н. Александра Алексеевича Редько - Карим_Хайдаров.
10.11.2021 - 12:35: ЭКОЛОГИЯ - Ecology -> Биологическая безопасность населения - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> Проблема государственного терроризма - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> ПРАВОСУДИЯ.НЕТ - Карим_Хайдаров.
10.11.2021 - 12:34: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вадима Глогера, США - Карим_Хайдаров.
10.11.2021 - 09:18: НОВЫЕ ТЕХНОЛОГИИ - New Technologies -> Волновая генетика Петра Гаряева, 5G-контроль и управление - Карим_Хайдаров.
10.11.2021 - 09:18: ЭКОЛОГИЯ - Ecology -> ЭКОЛОГИЯ ДЛЯ ВСЕХ - Карим_Хайдаров.
10.11.2021 - 09:16: ЭКОЛОГИЯ - Ecology -> ПРОБЛЕМЫ МЕДИЦИНЫ - Карим_Хайдаров.
10.11.2021 - 09:15: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Екатерины Коваленко - Карим_Хайдаров.
10.11.2021 - 09:13: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вильгельма Варкентина - Карим_Хайдаров.
Bourabai Research Institution home page

Боровское исследовательское учреждение - Bourabai Research Bourabai Research Institution