Calling `std.math.clamp` gives compile error `error: unable to evaluate constant expression` in Zig

1.1k Views Asked by At

Why does this program fail to compile? Zig version 0.6.0.

const std = @import("std");
fn get_value () f32 {
    return 1.0;
}
test "testcase" {
    const value: f32 = 1. + get_value() ;
    _ = std.math.clamp(value, 0.0, 255.0);
}

Gives compile error:

$ zig test src/clamp.zig       
Semantic Analysis [790/1017] ./src/clamp.zig:9:24: error: unable to evaluate constant expression
    _ = std.math.clamp(value, 0.0, 255.0);
                       ^
./src/clamp.zig:9:23: note: referenced here
    _ = std.math.clamp(value, 0.0, 255.0);
                      ^
1

There are 1 best solutions below

1
On BEST ANSWER

The reason is that value has different type than the constants 0.0 and 255.0. value is f32, and the type for the constants is comptime_float.

The fix is to cast the constants to f32.

_ = std.math.clamp(value, @as(f32, 0.0), @as(f32, 255.0));

Type of clamp seems to require that all parameters are either comptime values, or all are runtime values.

See https://ziglearn.org/chapter-1/#comptime