sub
subroutine - a procedure statement that marks the beginning and end of a subroutine
syntax
sub name([parameterlist]) [declarations] do [statements] [return] [statements] end
- name is the variable name up to 40 (ascii) characters long, that does not appear as any other variable name in the same program
- parameterlist contains the names of the simple variables and arrays passed to the subroutine when it is called
See also decl, call, func, parameters
details
A subroutine is a separate procedure, like a function. However, unlike a function, a subroutine cannot be used in an expression, as it does not return any value.
The keywords sub do .. end mark the beginning, execution block and end of the subroutine. As a whole, it is called a compound statement, or more accurately, an execution compound statement (ECS) as opposed to a declaration compound statement (DCS).
Subroutines are called by a call statement or by using the subroutine's name, optionally followed by an argument list.
In SharpBASIC subroutines can be recursive, which means that they can call themselves to perform a specific task. See the example below.
Subroutines can only be declared and defined at module level and optionally shared with other modules. See global and extern for more details.
example
The following example uses a recursive call to a subroutine to compute a factorial and passes a parameter by reference (see ref) to obtain the result. This example is for demonstration purposes. Typically, these kind of programming tasks to obtain a single result are done using functions.
' SharpBASIC subroutine recursion programming example
' ---------------------------------------------------
incl "lib/sys.sbi";
decl sub factorial(n:uint, ref result:uint);
dim result:uint;
main do
factorial(5, result);
print(result);
end
sub factorial(n:uint, ref result:uint)
do
if n > 0 do
call factorial(n - 1, result);
result :* n;
else do
result = 1;
end
end
Output:
120