🎓 A1Learner
🔍
0 of 46 lessons completed

Zig Debug Assertions

A debug assertion is a check that states a fact a program relies on. It runs in debug builds and stops the program if the fact is false.

Guard a function input

The assertion states the input must be below 100. The input 5 passes, so the function returns 10.

const std = @import("std");
fn double(n: u32) u32 {
    std.debug.assert(n < 100);
    return n * 2;
}
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{d}\n", .{double(5)});
}

Guard a loop index

The assertion states every index stays inside the array. All four indexes pass, so the sum prints.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const data = [_]u32{ 2, 4, 6, 8 };
    var sum: u32 = 0;
    var i: usize = 0;
    while (i < data.len) : (i += 1) {
        std.debug.assert(i < data.len);
        sum += data[i];
    }
    try out.print("{d}\n", .{sum});
}

Guard the result

The assertion after the computation states the result must match the expected value. The result 42 passes, so it prints.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const result: u32 = 40 + 2;
    std.debug.assert(result == 42);
    try out.print("{d}\n", .{result});
}

Example

const std = @import("std");
fn scaled(n: u32) u32 {
    std.debug.assert(n > 0);
    std.debug.assert(n < 100);
    const result = n * 2;
    std.debug.assert(result == n + n);
    return result;
}
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{d}\n", .{scaled(5)});
}

Key points

  • Debug assertion: a debug assertion is a check that a condition holds, written with std.debug.assert.
  • Invariant: an invariant is a fact that must stay true at a certain point in a program.
  • Precondition: a precondition is a fact that must be true before a function runs.
  • Postcondition: a postcondition is a fact that must be true after a function finishes.
  • Debug build: a debug build is a build made for finding mistakes, with assertions active.
  • Silent pass: a silent pass is an assertion that holds and prints nothing.

The first assertion guards the input before the work starts. The second assertion guards the result after the work finishes. Both pass, so the program prints 10 and nothing else.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when a debug assertion holds?