Cinder by Example

Cinder is small programming language for low-level development.

Control Flow

if / else

use "std/io.cnd";

fn main() -> i32 {
    let temp = 24;
    if temp > 30 {
        println("hot");
    } else if temp > 20 {
        println("warm");
    } else {
        println("cold");
    }
    return 0;
}
$ ./ifelse
warm

if as an expression

An if can produce a value. Both branches must have the same type.

use "std/io.cnd";

fn main() -> i32 {
    let n = 7;
    let label = if n % 2 == 0 { "even" } else { "odd" };
    println(label);
    return 0;
}
$ ./ifexpr
odd

loop

loop repeats forever. break stops it, continue jumps to the next

iteration.

use "std/io.cnd";

fn main() -> i32 {
    let mut i = 0;
    let sp: []u8 = " ";
    let mut first = true;
    loop {
        i += 1;
        if i % 2 == 0 { continue; }
        if i > 7 { break; }

        if !first { print(&sp, .S); }
        first = false;

        let v = i;
        print(&v, .I32);
    }
    putchar(10);

    return 0;
}
$ ./loop
1 3 5 7

while

use "std/io.cnd";

fn main() -> i32 {
    let mut n = 1;
    while n < 100 {
        n *= 2;
    }

    print(&n, .I32);
    putchar(10);
    return 0;
}
$ ./while
128

for over ranges

0..10 is exclusive, 0..=10 is inclusive. The loop variable is i32

(or the annotated type).

use "std/io.cnd";

fn main() -> i32 {
    let mut sum = 0;
    for i in 0..=10 {
        sum += i;
    }

    print(&sum, .I32);   // 0+1+...+10 = 55
    putchar(10);
    return 0;
}
$ ./forrange
55

A usize range is useful for indexing.

use "std/io.cnd";

fn main() -> i32 {
    let s = "abc";
    for i in 0usize..s.len {
        let v: i32 = s[i] as i32;
        print(&v, .I32);
    }
    putchar(10);
    return 0;
}
$ ./foridx
979899

for over values

The for v in coll form iterates arrays, slices, and strings.

use "std/io.cnd";

fn main() -> i32 {
    let primes = [2, 3, 5, 7];
    let mut total = 0;
    for p in primes {
        total += p;
    }

    print(&total, .I32);
    putchar(10);
    return 0;
}
$ ./foriter
17

switch

switch can match integers, integer ranges, enums, and strings. A final

else handles everything else.

use "std/io.cnd";

fn main() -> i32 {
    let code = 2;
    switch code {
        0 => println("zero");
        1..3 => println("small");
        else => println("large");
    }
    return 0;
}
$ ./switch
small

Switch cases are alternatives; execution does not fall through to the next

case. See Enums for enum matching.