Loops (v0.2.1)

while, for, and loop constructs for repeated execution.

Latest

Overview

Loops repeat a block while a condition holds, while a counter changes, or until the code breaks out explicitly.

In Thrust, loop state is usually visible in local variables. That makes it easy to see how the loop starts, changes, and stops.

Keep loops simple when they work with arrays or pointers. Small, direct loops are easier to check for off-by-one mistakes.

Primary source: syntax/loops/

Syntax Signatures

while index < length {
    index++;
}

for var i: s32 = 0; i < 10; i++; {
    total += i;
}

loop {
    if done {
        break;
    }
}

Behavior and Use

Use while when the condition is the main part of the loop. Use for when the initializer, condition, and step belong together. Use loop when the exit condition is inside the body.

Use break and continue sparingly. They are helpful, but too many exits make a loop harder to follow.

Best Practices

Loop Forms

Use the loop form that matches where the exit condition lives.

State and Bounds

Loop state should be visible and updated in one predictable place.

Example

fn sumTo(n: s32) s32 @public {
    var i: s32 = 0;
    var acc: s32 = 0;

    while i <= n {
        acc += i;
        i++;
    }

    return acc;
}

Back to language reference