Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Control Flow and Functions

Functions

Learn to write Zig functions: parameters are constants, return types, multiple results with structs, recursion, function pointers, anytype, inline, noreturn and doc comments.

Functions are where Zig's explicitness pays off. Every parameter has a type, every return type is spelled out, parameters cannot be modified, and nothing is overloaded: one name, one function. If you know how a function behaves from its signature alone, reading code becomes much faster.

Defining and calling

ZIG
const std = @import("std");

fn add(a: i32, b: i32) i32 {
    return a + b;
}

fn greet(name: []const u8) void {
    std.debug.print("Hello, {s}!\n", .{name});
}

pub fn main() void {
    const total = add(2, 3);
    greet("Zig");
    std.debug.print("total = {d}\n", .{total});
}
TEXT
Hello, Zig!
total = 5

The shape is fn name(param: Type, ...) ReturnType { body }. Functions without pub are private to the file. A function that returns nothing uses void.

You must use the returned value or discard it explicitly with _ = add(1, 2);. A call like add(1, 2); alone is a compile error because ignoring results silently hides bugs, especially ignored errors.

Parameters are constants

Inside the function you cannot assign to a parameter:

ZIG
fn bad(x: i32) i32 {
    x += 1;       // error: cannot assign to constant
    return x;
}

fn good(x: i32) i32 {
    var y = x;    // make a mutable copy
    y += 1;
    return y;
}

This rule lets the compiler choose how to pass values. Small values are passed in registers; large structs may be passed by reference under the hood, and because parameters are immutable the difference is unobservable. To let a function change the caller's data, pass a pointer:

ZIG
fn increment(counter: *u32) void {
    counter.* += 1;
}

pub fn main() void {
    var count: u32 = 0;
    increment(&count);
    increment(&count);
    // count == 2
}

Pointers have their own lesson in the next chapter.

Returning several values

Zig has no multiple return values, but a struct or tuple does the job:

ZIG
const MinMax = struct { min: i32, max: i32 };

fn minMax(values: []const i32) MinMax {
    var result = MinMax{ .min = values[0], .max = values[0] };
    for (values[1..]) |v| {
        if (v < result.min) result.min = v;
        if (v > result.max) result.max = v;
    }
    return result;
}

pub fn main() void {
    const r = minMax(&[_]i32{ 7, 2, 9, -4, 5 });
    std.debug.print("min {d}, max {d}\n", .{ r.min, r.max });
}

Output: min -4, max 9. An anonymous tuple works too: return .{ lo, hi }; with the return type written as struct { i32, i32 }, accessed as r[0] and r[1].

Recursion

Functions can call themselves. Remember there is no tail-call guarantee and stack space is limited, so deep recursion belongs in loops.

ZIG
fn factorial(n: u64) u64 {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

fn fibonacci(n: u32) u32 {
    return if (n < 2) n else fibonacci(n - 1) + fibonacci(n - 2);
}

factorial(10) is 3628800. For recursive functions whose depth the compiler cannot bound, Zig may require an explicit error set or type annotation, because it needs to infer the return type.

Function pointers and callbacks

A function's type is written fn (A, B) R. You can pass functions as values, which gives you callbacks without any extra syntax:

ZIG
fn apply(f: *const fn (i32) i32, x: i32) i32 {
    return f(x);
}

fn square(x: i32) i32 {
    return x * x;
}

pub fn main() void {
    std.debug.print("{d}\n", .{apply(square, 9)});
}

Output: 81. In Zig 0.15 you write *const fn (i32) i32 for the pointer type; plain fn (i32) i32 is the function body type used for comptime parameters.

anytype and comptime parameters

A parameter of type anytype accepts a value of any type, decided at each call site:

ZIG
fn describe(value: anytype) void {
    std.debug.print("{any} has type {s}\n", .{ value, @typeName(@TypeOf(value)) });
}

A comptime parameter must be known during compilation and lets a function take a type as an argument. Both are the foundation of Zig's generics and are covered in the Comptime and Generics chapter.

Visibility, doc comments and attributes

ZIG
/// Returns the square of `x`.
pub fn square(x: i32) i32 {
    return x * x;
}

inline fn fastPath() void {}     // force inlining
noinline fn slowPath() void {}   // forbid inlining
fn die() noreturn {              // never returns
    @panic("fatal");
}

noreturn is the type of expressions like return, break, @panic and unreachable. It fits into any type, which is why const x = if (ok) 5 else @panic("bad") type-checks. Zig inlines automatically where it is useful, so inline is rarely needed.

Calling conventions and exporting

export fn makes a function callable from C with the C calling convention, and extern fn declares one defined elsewhere. These are shown in the C interop chapter.

Stand-ins you can run

C's function syntax is the same idea with the types on the other side. The pointer parameter and struct return mirror the Zig examples above.

C Stand-in (C): pointer parameter, struct result, function pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust Stand-in (Rust): recursion and callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Can you assign to a function parameter inside the function?

    Zig parameters are immutable, which lets the compiler pass them however is fastest.
  2. 2. What happens if you call compute(); and ignore its non-void result?

    Unused results are errors, which prevents silently ignoring failures.
  3. 3. How can a function modify a caller's variable?

    Pass &variable and write through ptr.*.
  4. 4. How do you return two values from a function?

    A struct with named fields, or an anonymous tuple, carries multiple values.
  5. 5. What is the type of @panic("x")?

    noreturn marks expressions that never complete normally, so it coerces to any type.

Summary

  • fn name(p: T) R { ... }; pub exports; no overloading, no default arguments.
  • Parameters are constants; use pointers to modify caller data.
  • Return structs or tuples for several results; results must be used or discarded with _.
  • Functions are values: pass *const fn (A) R for callbacks.
  • anytype and comptime parameters open the door to generics; noreturn marks functions that never return.

Next: defer and errdefer