Skip to content
Subroutines and Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readSubs, Functions, and Types

FreeBASIC distinguishes:

  • Sub — does work, no return value
  • Function — returns a value
Sub Greet(name AS STRING)
    PRINT "Hello, " + name
End Sub

Function Square(n AS INTEGER) AS INTEGER
    Return n * n
End Function

Greet("Ada")
PRINT Square(5)

Functions return via Return (modern) or by assigning to the function name (classic):

Function Cube(n AS INTEGER) AS INTEGER
    Cube = n * n * n        ' classic style
End Function

Pass-by-reference with BYREF:

Sub Swap(BYREF a AS INTEGER, BYREF b AS INTEGER)
    DIM tmp AS INTEGER
    tmp = a
    a = b
    b = tmp
End Sub

Default is BYVAL (by value). BYREF is required for output parameters.

Default arguments:

Function Greet(name AS STRING, greeting AS STRING = "Hello") AS STRING
    Return greeting + ", " + name
End Function

PRINT Greet("Ada")              ' Hello, Ada
PRINT Greet("Ada", "Hi")        ' Hi, Ada

Recursion works fine — no special keyword needed.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…