liveBook · Manning

Null

As explained in Systems Programming with Zig

Null is a value representing the absence of an object or valid pointed-to item.

Null represents the absence of a valid pointed-to object. Zig makes nullability explicit in types and checks it, helping prevent nullable C values from reaching code that does not expect them. section 1.2.1

At C boundaries, nullable pointers can signal failure: creating a recipe book returns an optional pointer that is null if allocation fails. Loading returns null for file-open, allocation, or deserialization failures, so callers should check before use. section 5.3.1 section 5.4.3

Null is compact but gives little information about why something failed. Error codes can distinguish causes, such as running out of memory or requesting an invalid recipe ID. section 5.4.1

When using GLFW, pointer-returning functions use C NULL to indicate errors; check these values manually for reliable Zig code. section 7.3.1

Listing 5.3 An object without methods
const std = @import("std");

var gpa: std.heap.SafeAllocator(.{}) = .init; #1
var threaded: std.Io.Threaded = .init_single_threaded;

export fn recipes_quit() void {
    _ = gpa.deinit(); #2
    threaded.deinit();
    gpa = .init; #3
    threaded = .init_single_threaded;
}

const RecipeBook = struct {}; #4

export fn recipe_book_create() ?*RecipeBook { #5
    const ally = gpa.allocator();
    const book = ally.create(RecipeBook) catch {
        return null; #6
    };
    book.* = .{}; #7
    return book;
}

export fn recipe_book_close(book: *RecipeBook) void { #8
    const ally = gpa.allocator();
    book.deinit(ally); #9
    ally.destroy(book);
}

See an exported creation function return ?*RecipeBook and return null when allocation fails. section 5.3.1

How Systems Programming with Zig covers it

How deep it goes
Explains explicit optional-pointer typing and failure signaling, then contrasts null with more informative error codes.
Examples
Uses recipe-book creation and loading failures, plus GLFW window creation, to demonstrate null checks.
What you can do after
Apply it by checking optional pointers returned by Zig FFI and GLFW calls before use.
How it connects
Connects optional pointers to the C ABI, allocation failure, error codes, and GLFW pointer-return conventions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.