Library reference

Keep a number within two limits

Return the lower limit when a value is too small and the upper limit when it is too large. A value between them stays the same.

std.math.clamp

Simple example

Keep eight between one and five.

Start8 · 1–5
Result5
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.math.clamp(@as(i64, 8), 1, 5)});
}
Output
5
Advertisements

Everyday examples

The screen brightness slider runs from one to ten. What setting should it display when given 14?

Start14 · 1–10
Result10
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.math.clamp(@as(i64, 14), 1, 10)});
}
Output
10

A classroom heater accepts settings from 18 to 24 degrees. Which setting does it use when asked for 15?

Start15 · 18–24
Result18
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.math.clamp(@as(i64, 15), 18, 24)});
}
Output
18

A volume control runs from zero to ten. Which value appears when you choose six?

Start6 · 0–10
Result6
lesson.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("{any}\n", .{std.math.clamp(@as(i64, 6), 0, 10)});
}
Output
6
Run the example
Terminal
zig run lesson.zig
Official documentation