How to determine if a number is within a range?

I have a (signed) number n. How do I determine if my number is in the range [minval, maxval)?

The obvious, C-like answer is just

if (minval <= n and n < maxval) {...}

I’m wondering if there is any syntactic sugar, language feature, stdlib type, etc. that supports ranges and/or containment?

(For example, chained operators min <= n < max, or an in operator with a Range(min, max) type, or …?)

To my knowledge, there’s no range type in Zig per se, so in an if condition, the only way is with the and logical operator you mentioned. There is however a range test when working in a switch:

const in_range = switch(n) {
    30...50 => true,
    else => false,
};

Note that the range is inclusive so in this example it’s like 30 <= n and n <= 50 .

3 Likes