Zig Loops

In Zig, loop structures includewhileloops andforloops. Each loop has its specific syntax and usage. The following details both loop structures, including their syntax, description, and examples.

1、whileLoops

Syntax

while (condition) : (increment) {
    // code block
}
  • condition: a boolean expression. As long as it istrue, the loop will continue to execute.
  • increment(optional): an expression executed after each loop iteration ends.

Description

whileThe loop checks the condition before each iteration. If the condition istrue, it executes the code in the loop body. After the loop body finishes, execute theincrementexpression (if any). Then check the condition again until it isfalse。

Example

Example

const std = @import("std");

pub fn main() void {
    var i: i32 = 0;
    while (i < 5) : (i += 1) {
        std.debug.print("i: {}\n", .{i});
    }
}

Analysis:

  • Initialize variableito 0.
  • As long asiis less than 5, the loop body will execute.
  • After each loop iteration,iincrements by 1.

The compiled execution result is:

i: 0
i: 1
i: 2
i: 3
i: 4

2、forLoop

Syntax

for (collection) |item, index| {
    // code block
}
  • collection: an array, slice, or other iterable collection.
  • item: the current element of the collection in each iteration.
  • index(optional): the index of the current element.

Description

forThe loop is used to iterate over each element in a collection. In each iteration, the current element is assigned toitem, and the code in the loop body is executed.

Example

Example

const std = @import("std");

pub fn main() void {
    const array = [5]i32{ 1, 2, 3, 4, 5 };
    var index: usize = 0; // The index variable needs a declared type
    for (array) |item| {
        std.debug.print("index: {}, item: {}\n", .{ index, item });
        index += 1; // Update index
    }
}

Analysis:

  • Defines an array containing 5 integers.
  • Usingforloop to iterate over each element in the array, assigning the element value toitem, and the index toindex。
  • In the loop body, print the value and index of each element.

The compiled execution result is:

index: 0, item: 1
index: 1, item: 2
index: 2, item: 3
index: 3, item: 4
index: 4, item: 5

3、continueandbreak

Syntax

  • continue: skips the current iteration and continues to the next one.
  • break: terminates the loop.

Description

continueis used to skip the remaining code in the current iteration and immediately start the next iteration.breakis used to terminate the entire loop.

Example

Example

const std = @import("std");

pub fn main() void {
    var i: i32 = 0;
    while (i < 10) : (i += 1) {
        if (i == 5) {
            continue; // Skip the iteration where i equals 5
        }
        if (i == 8) {
            break; // Terminate the loop
        }
        std.debug.print("i: {}\n", .{i});
    }
}

Analysis:

  • WheniWhen it equals 5,continueskips that iteration.
  • WheniWhen it equals 8,breakterminates the loop.

The compiled execution result is:

i: 0
i: 1
i: 2
i: 3
i: 4
i: 6
i: 7

5. Nested Loops

Syntax

for (outer_collection) |outer_item| {
    for (inner_collection) |inner_item| {
        // code block
    }
}

Description

A loop containing another loop within its body is called a nested loop. The inner loop is executed during each iteration of the outer loop.

Example

Example

const std = @import("std");

pub fn main() void {
    // Declare an array containing three strings
    const letters = [_][]const u8{ "A", "B", "C" };
    // Iterate over the array
    for (letters) |letter| {
        var count: i32 = 0; // Declare a counter
        // Use a while loop to print each letter and the count
        while (count < 3) : (count += 1) {
            std.debug.print("{s} - {}\n", .{ letter, count });
        }
    }
}

Analysis:

  • The outerforloop iterates over the array of letters.
  • The innerwhileloop executes 3 times, printing the letter and the count.

The compiled execution result is:

A - 0
A - 1
A - 2
B - 0
B - 1
B - 2
C - 0
C - 1
C - 2

6. More Loops

Infinite Loop

You can create an infinite loop using a while loop, as long as the condition is always true:

Example

pub fn main() void {
    while (true) {
        // Code block
        // Must contain some exit mechanism, otherwise the program will run forever
    }
}

Range Loop

Zig also allows you to loop over ranges, which can simplify code in some cases:

Example

pub fn main() void {
    for (0..10) |i| {
        std.debug.print("i: {}\n", .{i});
    }
}

Labeled Loop

Zig supports labeled loops, allowing you to name loops, which is very useful in nested loops:

Example

pub fn main() void {
    loop: while (true) {
        while (true) {
            std.debug.print("Inside nested loop\n");
            break :loop; // Exit the outer loop
        }
    }
}
Other Extensions