Loops (v0.2.1)
while, for, and loop constructs for repeated execution.
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
- Keep loop assumptions simple and visible near the loop.
- Move values that do not change outside the loop.
- Check bounds clearly when iterating over arrays.
Loop Forms
Use the loop form that matches where the exit condition lives.
- while is best when the condition is checked before every iteration.
- for keeps initializer, condition, step, and body together.
- loop repeats until a break or return exits from inside the body.
State and Bounds
Loop state should be visible and updated in one predictable place.
- Keep counters and limits close to the loop header.
- When indexing arrays or pointers, compare against the known length before the access.
- Move invariant calculations before the loop to make the body easier to inspect.
Example
fn sumTo(n: s32) s32 @public {
var i: s32 = 0;
var acc: s32 = 0;
while i <= n {
acc += i;
i++;
}
return acc;
}