← Back to AILP Home

for-in

for x in <iterable> walks a range or an array, binding each element to x in turn. It is the most direct form when you want the elements themselves rather than an index.

Ranges

func:failsafe = int32(tbb32:err) {
    exit 1;
};

func:main = int32() {
    int32:total = 0i32;
    for v in 0i32..5i32 {
        total += v;   // v = 0, 1, 2, 3, 4
    }
    exit total;       // 10
};

The range a..b yields a up to but not including b, matching the exclusive upper bound of loop and till.

Arrays

func:main = int32() {
    [int32; 3]:xs = [4i32, 5i32, 6i32];
    int32:total = 0i32;
    for v in xs {
        total += v;
    }
    exit total;       // 15
};

Element binding

x is a fresh binding per iteration, scoped to the body. For arrays it holds a copy of the element value for scalar element types; mutating x does not write back into the array. To modify elements in place, index the array directly inside a counted loop.

break and continue

break and continue work in for-in exactly as in the other forms: break leaves the loop, continue advances to the next element. See break and continue.

Next: break and continue.