A function is a callable sequence of instructions that returns control to its caller. In Zig, its body is a curly-braced block whose statements execute in order when called. Runtime code lives inside functions; runtime calls ultimately trace back to main. section 2.1
A Zig function definition names its parameters, their types, and its return type. Parameters are always const. A return statement in a non-void function must supply a value matching the return type; otherwise, the code will not compile. section 2.1.3
Listing 2.2 Recursive fibonacci
const std = @import("std");
fn fibonacci(n: usize) i32 { // #1
// #2
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2); // #3
}
pub fn main() void {
// #4
const first = fibonacci(1);
const second = fibonacci(2);
const third = fibonacci(3);
const fourth = fibonacci(4);
std.debug.print("{} {} {} {}\n", .{ first, second, third, fourth });
}
The recursive fibonacci function takes a usize index and returns an i32. Its base cases return 0 and 1; otherwise, it calls itself twice. The main function calls it and prints the results. section 2.1.3
The Fibonacci example is intuitive, not fast: recursive calls repeat work. A sufficiently large result also triggers a runtime overflow panic; try n = 47, but expect a wait. section 2.1.3
A call stack can make the return trip explicit. In a CHIP-8 interpreter, a call saves the current program counter on the stack and jumps to the subroutine; a return pops the saved address back into the program counter. Registers can carry data between them; standardizing that exchange leads toward an ABI. section 6.5.6
For CHIP-8, instruction 2MMM calls the address MMM, and 00EE returns. One implementation stores the stack in reserved interpreter memory: pushing the 12-bit program counter uses two bytes and advances the stack pointer by two; popping reverses those steps. Reset the pointer when loading a program. section 6.5.6
Functions can also form the exposed operations of a library API, alongside its data structures. Choose those operations to match the behavior the API needs to provide and its users’ expectations. section 5.3

























