Skip to content
Subs and Functions
step 1/5

Reading — step 1 of 5

Learn

~2 min readSubs, Functions, Arrays

BASIC distinguishes:

  • SUB — procedure, no return value
  • FUNCTION — returns a value

SUB

SUB Greet(who AS STRING)
    PRINT "Hello, "; who
END SUB

' Call:
Greet("Ada")
' or:
CALL Greet("Ada")

FUNCTION

FUNCTION Square(n AS INTEGER) AS INTEGER
    Square = n * n         ' assign to function name = return
END FUNCTION

FreeBASIC also accepts RETURN:

FUNCTION Cube(n AS INTEGER) AS INTEGER
    RETURN n * n * n
END FUNCTION

DECLARE for forward references

If you call a function/sub before it's defined in the file, declare it first:

DECLARE FUNCTION Square(n AS INTEGER) AS INTEGER

PRINT Square(5)            ' OK — declared above

FUNCTION Square(n AS INTEGER) AS INTEGER
    RETURN n * n
END FUNCTION

BYVAL vs BYREF

SUB Increment(BYREF n AS INTEGER)
    n = n + 1
END SUB

DIM x AS INTEGER
x = 5
Increment(x)
PRINT x                    ' 6

In FreeBASIC's default dialect, numeric parameters are passed BYVAL unless you mark them BYREF — that is why Increment above says BYREF explicitly. (Strings default to BYREF; the old QB dialect passed everything BYREF.)

Recursion

FUNCTION Factorial(n AS INTEGER) AS LONGINT
    IF n <= 1 THEN
        RETURN 1
    ELSE
        RETURN n * Factorial(n - 1)
    END IF
END FUNCTION

Calling a function from itself works as you'd expect.

Default values (FreeBASIC extension)

FUNCTION Greet(who AS STRING, greeting AS STRING = "Hello") AS STRING
    RETURN greeting & ", " & who
END FUNCTION

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

Variadic — ...

FreeBASIC supports C-style variadic parameters (declared with ...), read with the cva_list/cva_arg macros. Beware old tutorials that walk the stack with VARPTR pointer arithmetic — that trick breaks on 64-bit systems, where arguments travel in registers, not on the stack.

You will rarely need variadics: idiomatic BASIC passes an array instead.

SUB vs FUNCTION return

The old BASIC trick — assign to the function name:

FUNCTION Square(n AS INTEGER) AS INTEGER
    Square = n * n         ' this is the return
END FUNCTION

Works but RETURN expr is clearer. Use RETURN in new code.

Discussion

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

Sign in to post a comment or reply.

Loading…