0

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);
                      ^
Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183

1 Answers1

1

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

Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
  • 2
    This seems no longer necessary in zig 0.7.0. I tried to run your code and got no compiler error. All parameters of `clamp` are `anytype` and get casted by the `Min` function. See [clamp in the standard library](https://github.com/ziglang/zig/blob/a05ae01b4fba950fa0bddb8e33ed757b592d9b47/lib/std/math.zig#L391). – jackdbd Nov 24 '20 at 08:12