Step 1 of 5 · Reading · ~3 min
Learn
Subs, Functions, Arrays
Subs and Functions
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, and that is what to use in new code — it says plainly what is happening:
FUNCTION Cube(n AS INTEGER) AS INTEGER
RETURN n * n * n
END FUNCTION
DECLARE for forward references
If you call a function or sub before it is defined in the file, declare it first:
DECLARE FUNCTION Square(n AS INTEGER) AS INTEGER
PRINT STR(Square(5)) ' OK — declared above
FUNCTION Square(n AS INTEGER) AS INTEGER
RETURN n * n
END FUNCTION
Printing what a FUNCTION returns
A function that returns a number is still a number, so the sign column from the Variables lesson applies to it too:
PRINT Square(5) ' writes " 25" — leading space, test fails
PRINT STR(Square(5)) ' writes "25" — what the grader wants
This is the most expensive mistake on this lesson: the arithmetic is right, the output looks right on screen, and the test still says wrong answer over one invisible space.
BYVAL vs BYREF
SUB Increment(BYREF n AS INTEGER)
n = n + 1
END SUB
DIM x AS INTEGER
x = 5
Increment(x)
PRINT STR(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. Drop the BYREF and the SUB increments its own private copy while x stays 5. (Strings default to BYREF; the old QB dialect passed everything BYREF, which is why old listings never mark it.)
Recursion
FUNCTION Factorial(n AS INTEGER) AS LONGINT
IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * Factorial(n - 1)
END IF
END FUNCTION
A function may call itself. Two parts are mandatory: a base case that returns without recursing, and a recursive step that moves the argument toward that base case. Leave the base case out and the calls never stop — the stack fills up and the program dies.
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"
Your exercise
Write Power(bx, ex) recursively. BASE and EXP are reserved words in FreeBASIC, which is why the parameters are named bx and ex — renaming them back will not compile.
The shape is the one in the Recursion section: decide what Power returns once ex has reached its base case, and otherwise express bx-to-the-ex in terms of a smaller exponent. Do not reach for ^; the point is the recursion. The starter's RETURN 1 is a placeholder that compiles — it answers 1 for every input, which happens to be right for exactly one of the three tests.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…