Procedures Overview

FreeBASIC

Procedures Overview
 
Overview of the different FB procedure types.

Procedures are blocks of code that can be executed, or called, from anywhere in a program, any number of times. The code that is executed is called the procedure body. There are two types of procedures in FreeBASIC: procedures that don't return a value and procedures that do.

Subs

Subs are procedures that don't return values. They are declared using the Declare keyword, and defined using the Sub keyword. Declaring a procedure introduces its name so that it can be called, and a procedure definition lists the statements of code that will be executed when called. A sub is called simply by using its name somewhere in the program.

' introduces the sub 'MyProcedure'
Declare Sub MyProcedure

' calls the procedure 'MyProcedure'
MyProcedure

' defines the procedure body for 'MyProcedure'
Sub MyProcedure
    Print "the body of MyProcedure"
End Sub

will produce the output:

the body of MyProcedure

Notice that only the declaration is needed to call the procedure. The procedure can be defined later in code, or even in a different source file altogether.

Functions

Functions are procedures that return a value back to the point in code in which they are called. You can think of a function call as evaluating to some expression, just like a variable or object. They are declared using the Declare keyword, and defined using the Function keyword. The type of value that functions return is specified at the end of the declaration.

' introduces and defines a procedure that returns an integer value
Function MyProcedure As Integer
    Return 10
End Function

' calls the procedure, and stores its return value in a variable
Dim i As Integer = MyProcedure
Print i

will produce the output:

10
Since a definition is a declaration, a procedure can be called after it has been defined, as well.

It is a common convention when calling a procedure to place parenthesis '()' after the procedure name, to signify a procedure call. FreeBASIC does not require this, however.

See also