liveBook · Manning

Switch statement

As explained in Systems Programming with Zig

A switch statement is a control-flow construct that selects code to execute based on an expression's matching case.

A switch statement routes execution according to a value. In a CHIP-8 interpreter, switching on the instruction’s first nibble starts the decoding process; each case can implement an instruction, while an `else` branch can return `error.UnknownInstruction`. section 6.5.3

Switches also pair with enums to handle distinct options. When every enum case is covered, Zig can omit `else` and alert you at compile time if a newly added variant needs another branch. section 5.2.4

Listing 6.16 Set the I register
switch (nibbles[0]) {
    0xA => {
        // set I to const #1
        const addr: u12 = (@as(u12, nibbles[1]) << 8) + bytecode[1]; #2
        memory.i = addr; #3
    },
    else => {
        return error.UnknownInstruction; #4
    }
}

See a CHIP-8 decoder case that builds an address from instruction bytes, sets the I register, and rejects unknown instructions. section 6.5.3

How Systems Programming with Zig covers it

How deep it goes
Demonstrates nibble-based dispatch and enum exhaustiveness, without detailing switch implementation internals.
Examples
Shows a CHIP-8 case setting the I register and enum cases selecting arithmetic operations.
What you can do after
Apply Zig switches to decode CHIP-8 instructions or dispatch enum-specific behavior.
How it connects
Connects switch statements to enums, instruction decoding, and CHIP-8 interpretation.

Also explained in

Compare how 11 books explain switch statement →

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.