typestar

for loops in Odin

for is Odin's only loop, wearing three costumes: range, C-style, and for-in.

package main

import "core:fmt"

main :: proc() {
    // for is the only loop; ..< is a half-open range.
    for lap in 1..=4 {
        fmt.println("sled dog lap", lap)
    }

    // The C-style form still works when you need the knobs.
    for bell := 6; bell > 0; bell -= 2 {
        fmt.println("bells:", bell)
    }

    // Range over a value: element and index come out together.
    for temp, day in ([4]int{61, 68, 74, 79}) {
        fmt.printfln("day %d: %d F", day + 1, temp)
    }
}

How it works

  1. for lap in 1..=4 walks an inclusive range; ..< would stop early.
  2. The C-style init; cond; post form remains for counting down bells.
  3. Ranging over an array yields element and index together.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
432
Tokens
98
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 84 seconds.

Type this snippet

Step 2 of 3 in Control flow, step 5 of 27 in Language basics.

← Previous Next →

for loops in other languages