← All examples

C enum convert

A number from C becomes a C enum only through a check.

c_enum_convert.zg
# A number from C becomes a C enum only through a check (owner, 2026-09-27). `to.Key[…]`
# converts it, failing `out_of_range` for a number no case has — here 302, a key a newer
# library added — so the program decides what an unknown key means instead of hitting
# undefined behaviour in the `match`. A callback, which C calls, takes the plain number.
layout.C enum Key { a = 65, b = 66, escape = 256 }
fn on_key ['code': int32] -> int32 {
    let 'k' := to.Key['code'] otherwise { out_of_range { return 0; } };
    match 'k' {
        a { return 1; }
        b { return 2; }
        escape { return 3; }
    }
}
MAIN {
    std::print.useful[on_key[66], " ", on_key[302], " ", on_key[256], newln];
}
Output
2 0 3