A question on a switch of a comptime known value

this is a function from my vector library, it sets the X axis of a vector (the first element in a SIMD vector) to the provided value.

question is: how would the compiler handles this given that dimensions is a comptime_int and so it is comptime known, would it make a copy of the function for each provided dimension? 2..4
or would the switch remain there?

pub fn setX(self: Vec, value: T) Vec {
    switch (dimensions) {
        2 => return Vec.new(value, self.y()),
        3 => return Vec.new(value, self.y(), self.z()),
        4 => return Vec.new(value, self.y(), self.z(), self.w()),
        else => comptime unreachable,
    }
}

I believe that in general a function is monomorphized (so a copy is made) based on its comptime arguments and its comptime captures. After that, there is no need to branch if comptime code execution can determine that dimensions never changes, so the switch won’t be lowered to a switch in assembly. You can verify this for yourself with tools like the godbolt compiler explorer

1 Like

You can ensure a switch or if always gets eliminated by adding comptime to the clause:

pub fn setX(self: Vec, value: T) Vec {
    switch (comptime dimensions) {
        2 => return Vec.new(value, self.y()),
        3 => return Vec.new(value, self.y(), self.z()),
        4 => return Vec.new(value, self.y(), self.z(), self.w()),
        else => comptime unreachable,
    }
}

If the compiler can’t select a single prong to compile, you’ll get a compile error.

3 Likes