Skip to content

Zig Functions

A function is a named piece of code you can run whenever you need it. Instead of copying the same five lines into three places, you write them once, give them a name, and call that name. You’ve already used one function in every program: main. In this lesson you’ll write your own, and you’ll see the few rules Zig is strict about, like always using a function’s result.

A function starts with fn, then its name, its parameters in parentheses, and its return type. The code it runs goes in braces:

const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
const total = add(2, 3);
std.debug.print("2 + 3 = {d}\n", .{total});
std.debug.print("10 + 20 = {d}\n", .{add(10, 20)});
}

Output:

2 + 3 = 5
10 + 20 = 30

Read fn add(a: i32, b: i32) i32 from left to right: a function called add takes two i32 values, calls them a and b, and gives back an i32. Each parameter needs a type, written like a variable’s type: name, colon, type. return a + b; hands the answer back to whoever called it.

To call a function, write its name and the values in parentheses: add(2, 3). The values you pass are called arguments. You can store the result in a variable, or use the call straight inside something else, like the second print.

Some functions do something (like printing) and don’t give anything back. Their return type is void:

const std = @import("std");
fn greet(name: []const u8) void {
std.debug.print("Hello, {s}!\n", .{name});
}
pub fn main() void {
greet("Ada");
greet("Linus");
}

Output:

Hello, Ada!
Hello, Linus!

[]const u8 is how Zig writes “some text” (you met it in Zig Strings). A void function doesn’t need a return: it simply ends at the closing brace. You can still write return; to leave early, as you saw in Zig Defer.

main is a function too. pub fn main() void means “a public function called main that takes nothing and returns nothing”. Zig calls it for you when the program starts.

If you say a function returns an i32, every path through it has to return one. Forget the return, and the build fails:

fn add(a: i32, b: i32) i32 {
const sum = a + b;
_ = sum;
}
pub fn main() void {
_ = add(1, 2);
}
main.zig:1:24: error: function with non-void return type 'i32' implicitly returns
fn add(a: i32, b: i32) i32 {
^~~
main.zig:4:1: note: control flow reaches end of body here
}
^

Some languages quietly return None, undefined or garbage here. Zig refuses, and the note points at the closing brace where your function “falls off the end”.

Calling a function that returns a value and then ignoring it is an error in Zig:

const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
add(1, 2);
}
main.zig:8:8: error: value of type 'i32' ignored
add(1, 2);
~~~^~~~~~
main.zig:8:8: note: all non-void values must be used
main.zig:8:8: note: to discard the value, assign it to '_'

This rule catches real bugs, like calling a function that returns an error and never checking it. If you really don’t need the value, say so on purpose with _ = add(1, 2);. That’s the same _ = you used for unused variables.

In C you have to declare a function before you call it. In Zig you don’t. Functions at the top level of a file can be written in any order, so many people put main first and the helpers below it:

const std = @import("std");
pub fn main() void {
std.debug.print("4 squared is {d}\n", .{square(4)});
std.debug.print("area of a 3 x 5 room: {d}\n", .{area(3, 5)});
}
fn square(x: i32) i32 {
return x * x;
}
fn area(width: u32, height: u32) u32 {
return width * height;
}

Output:

4 squared is 16
area of a 3 x 5 room: 15

Zig reads the whole file before it checks the calls, so main can use square even though square comes later.

A function that calls itself is recursive. The classic example is the factorial: 5! is 5 × 4 × 3 × 2 × 1, which is the same as 5 × 4!:

const std = @import("std");
fn factorial(n: u64) u64 {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
pub fn main() void {
std.debug.print("5! = {d}\n", .{factorial(5)});
std.debug.print("10! = {d}\n", .{factorial(10)});
}

Output:

5! = 120
10! = 3628800

Every recursive function needs a base case that stops it, here if (n <= 1) return 1;. Without one, the function calls itself forever, and each call uses a bit more of the stack (the memory for function calls) until it runs out:

const std = @import("std");
fn countUp(n: u32) u32 {
return countUp(n + 1);
}
pub fn main() void {
std.debug.print("{d}\n", .{countUp(0)});
}

You’ll see something like:

Segmentation fault at address 0x7ffc3b1e4ff0
main.zig:3:24: 0x11e5038 in countUp (main.zig)
fn countUp(n: u32) u32 {
^
main.zig:4:19: 0x11e5077 in countUp (main.zig)
return countUp(n + 1);
^
...

The program crashes with a stack overflow, and the trace shows countUp calling countUp over and over. The reference section on recursion has the official notes. For deep problems, a while loop is often safer than recursion, because a loop doesn’t eat stack space.

A Zig function returns one value. When you need two, return a small group of values called a tuple and unpack it at the call site:

const std = @import("std");
fn divide(a: u32, b: u32) struct { u32, u32 } {
return .{ a / b, a % b };
}
pub fn main() void {
const quotient, const remainder = divide(17, 5);
std.debug.print("17 / 5 = {d} remainder {d}\n", .{ quotient, remainder });
}

Output:

17 / 5 = 3 remainder 2

struct { u32, u32 } means “two u32 values in a row”, and .{ a / b, a % b } builds one. const quotient, const remainder = ... splits it into two names. Tuples get their own lesson in Zig Anonymous Structs & Tuples. When the values have meanings worth naming, a struct with named fields is clearer; you’ll learn those in Zig Structs.

Two things you might expect from other languages don’t exist in Zig:

  • Default parameter values. Every call passes every argument. If you leave one out, you get expected 2 argument(s), found 1.
  • Overloading. You can’t have two functions with the same name and different parameters:
fn add(a: i32, b: i32) i32 {
return a + b;
}
fn add(a: f64, b: f64) f64 {
return a + b;
}
pub fn main() void {
_ = add(1, 2);
}
main.zig:1:4: error: duplicate struct member name 'add'
fn add(a: i32, b: i32) i32 {
^~~
main.zig:5:4: note: duplicate name here
fn add(a: f64, b: f64) f64 {
^~~

“Struct member” sounds odd here, but every Zig file is secretly a struct, and its functions are its members. The fix is to give the functions different names (addInts, addFloats), or to write one function that works for many types, which you’ll see in Zig Function Parameters. It’s more typing, but you never have to work out which of five adds a call picked.

So far everything lived in one file. Bigger programs are split into several, and each file decides what others may use. A function is private to its file unless you mark it pub. Say you have two files side by side:

math.zig
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
fn secretHelper() i32 {
return 42;
}
main.zig
const std = @import("std");
const math = @import("math.zig");
pub fn main() void {
std.debug.print("2 + 3 = {d}\n", .{math.add(2, 3)});
}

Run it with zig run main.zig, and you’ll see:

2 + 3 = 5

@import("math.zig") loads the other file, and math.add calls its public function. Try math.secretHelper() instead, and Zig stops you:

main.zig:5:36: error: 'secretHelper' is not marked 'pub'
std.debug.print("{d}\n", .{math.secretHelper()});
~~~~^~~~~~~~~~~~~
math.zig:5:1: note: declared here
fn secretHelper() i32 {
^~~~~~~~~~~~~~~~~~~~~

That’s also why main is pub: the code that starts your program lives in the standard library, a different file, and it needs to see main. Files and imports get a full lesson in Zig Modules & Imports.

This one surprises everyone once. Zig compiles lazily: a function that nothing calls is never fully checked. This program builds and runs, even though neverCalled has an obvious type error:

const std = @import("std");
fn neverCalled() void {
const x: i32 = "hello";
_ = x;
}
pub fn main() void {
std.debug.print("it builds!\n", .{});
}

Output:

it builds!

The moment something calls neverCalled(), the error shows up. It keeps builds fast, and it’s what lets Zig code target many platforms without stubbing out everything. Some simple checks still run on every function, such as syntax and unused variables, so a missing brace or an unused const still fails the build. Type errors only show up once the function is used.

The language reference on functions lists everything a function declaration can have, including some things you’ll meet much later, like export and extern for talking to C.

Write a function isEven(n: u32) bool that returns true for even numbers. Call it for 4 and 7 and print the results.

Hint: n % 2 is the remainder after dividing by 2. Print a bool with {}.

Show solution
const std = @import("std");
fn isEven(n: u32) bool {
return n % 2 == 0;
}
pub fn main() void {
std.debug.print("4 is even: {}\n", .{isEven(4)});
std.debug.print("7 is even: {}\n", .{isEven(7)});
}

Output:

4 is even: true
7 is even: false

n % 2 == 0 is already a bool, so you can return it directly. There’s no need for an if.

Write maxOfThree(a: i32, b: i32, c: i32) i32 and use it on (4, 9, 2) and (-1, -5, -3). Write a max function for two numbers first, then build maxOfThree from it.

Hint: the biggest of three is max(a, max(b, c)).

Show solution
const std = @import("std");
fn max(a: i32, b: i32) i32 {
if (a > b) return a;
return b;
}
fn maxOfThree(a: i32, b: i32, c: i32) i32 {
return max(a, max(b, c));
}
pub fn main() void {
std.debug.print("{d}\n", .{maxOfThree(4, 9, 2)});
std.debug.print("{d}\n", .{maxOfThree(-1, -5, -3)});
}

Output:

9
-1

Small functions that call each other are easier to check than one big one. The standard library has this already as @max(a, b), a builtin, but writing it yourself is good practice.

Write a recursive power(base: u64, exp: u32) u64 so that power(2, 10) is 1024. Anything to the power of 0 is 1.

Hint: the base case is exp == 0. Otherwise, base to the exp is base * power(base, exp - 1).

Show solution
const std = @import("std");
fn power(base: u64, exp: u32) u64 {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}
pub fn main() void {
std.debug.print("2^10 = {d}\n", .{power(2, 10)});
std.debug.print("3^4 = {d}\n", .{power(3, 4)});
std.debug.print("7^0 = {d}\n", .{power(7, 0)});
}

Output:

2^10 = 1024
3^4 = 81
7^0 = 1

Each call makes exp one smaller, so it always reaches 0 and stops.

  • Write a function as fn name(param: Type) ReturnType { ... }; a function that gives nothing back returns void.
  • A function with a return type must return on every path, and callers must use the result (or write _ =).
  • Top-level functions can appear in any order in a file. Name them in camelCase.
  • Functions can be recursive, but always give them a base case, or the stack overflows.
  • To return several values, return a tuple and unpack it: const a, const b = f();.
  • No default arguments and no overloading: use different names, or anytype (next lesson).
  • Functions are private to their file unless marked pub, and Zig only fully checks functions that are actually used.

Next up: Zig Function Parameters, how values get into a function, and how a function can change your variables.

Quick check

1. What does fn area(w: u32, h: u32) u32 tell you?
2. You call add(1, 2); on a line by itself, and add returns an i32. What happens?
3. Can you call a function that is written further down in the same file?
4. A function in math.zig has no pub. Can main.zig call it after @import("math.zig")?