5.26 · exercise

call yourself

Write fact, a subroutine that computes a factorial by calling itself, and use it to print 10!.

Recursion is where the calling convention stops being theory. Each call to fact needs its own frame (lr must survive the recursive bl), and n has to outlive the recursive call, which means a callee-saved register that you save on entry and restore on exit. Base case first: when n is 1 or less, the answer is 1. Otherwise it is n * fact(n - 1).

what is checked

  • 10! printed on its own line
  • the program exits cleanly
  • a real call chain does it: a frame is built (stp) and the recursion happens (bl), with no precomputed answer

Specification

args
stdoutprints the expected output
exitexits with the expected code
sourceuses bl
sourceuses stp
sourcecomputes the result (does not hardcode it)

Checked by running your program against expected behavior, never by matching a stored solution.

loading editor...
Open in playground