Skip to content
📖 Auto vs Modern CBook contents

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
// 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
// Auto
fn max(a int, b int) int {
    if a > b { a } else { b }
}

Key differences:

FeatureCAuto
KeywordNone (return type first)fn
Return typeBefore function nameAfter parameter list
Parameter syntaxint a, int ba int, b int
Return statementreturn expr;Last expression or return
Empty parametersvoidEmpty ()
Missing returnUndefined behaviorCompile 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:

auto
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:

c
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:

auto
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 }
}

Released under the MIT License.