Chapter 7: Functions
Level 1 — Acquaintance
Encapsulating logic into reusable, composable units.
Functions are the primary mechanism for organizing code. A function takes inputs (parameters), performs computation, and produces an output (return value). C and Auto share the same fundamental model but differ in syntax, type expression, and safety guarantees.
7.1 Simple Functions
A C function has a return type, a name, a parameter list, and a body:
// C
int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}An Auto function uses the fn keyword with type annotations following parameter names:
// Auto
fn max(a int, b int) int {
if a > b { a } else { b }
}Key differences:
| Feature | C | Auto |
|---|---|---|
| Keyword | None (return type first) | fn |
| Return type | Before function name | After parameter list |
| Parameter syntax | int a, int b | a int, b int |
| Return statement | return expr; | Last expression or return |
| Empty parameters | void | Empty () |
| Missing return | Undefined behavior | Compile error |
Implicit return: In Auto, the last expression in a block is its value. There is no need for an explicit return keyword when the function body is a single expression or when the last expression is the intended return value:
fn square(x int) int {
x * x // implicit return
}
fn clamp(val int, lo int, hi int) int {
max(lo, min(val, hi)) // implicit return
}Forward declarations: In C, functions must be declared before use. This often requires forward declarations (prototypes) at the top of a file:
int min(int a, int b); // forward declaration
int max(int a, int b) { ... }
int clamp(int v, int lo, int hi) { return max(lo, min(v, hi)); }
int min(int a, int b) { return a < b ? a : b; }Auto does not require forward declarations. The compiler resolves function references in a single pass, so you can call a function before it is defined:
fn clamp(val int, lo int, hi int) int {
max(lo, min(val, hi))
}
fn max(a int, b int) int {
if a > b { a } else { b }
}
fn min(a int, b int) int {
if a < b { a } else { b }
}