Does some comptime condition help optimize away runtime function body?

const ENDIAN = builtin.cpu.arch.endian();

fn foo() void {
    if (ENDIAN == std.builtin.Endian.little) {
        // some runtime codes
    } else {
        // some runtime codes
    }
}

well, i think if (ENDIAN == std.builtin.Endian.little) will turn into if (true) or if (false) and compiler will be able to optimize it away…

but what if I had some switch cases based on some comptime variable, in that case will the compiler only generate the specific function body depending on that condition? or it will generate all the cases lazily?

It generates cases (based on comptime information) if they are evaluated. For instance, this code compiles:

const control: bool = false;

export fn square(num: i32) i32 {
    if (comptime control) {
        @compileError("I am an error.");
    }
    return num * num;
}

Same with this. If all branches were evaluated, this would result in a comiler error.

export fn square(num: i32) i32 {
    return switch (@typeInfo(@TypeOf(num))) {
        .Int => num * num,
        else => @compileError("This branch failed"),
    };
}

Meanwhile, this dies immediately because each branch is evaluated (not based on comptime information):

export fn square(num: i32) i32 {
    return switch (num) {
        42 => num * num,
        else => @compileError("This branch failed"),
    };
}
2 Likes

I didn’t quite get the each branch is evaluated part
fn square(num: i32) i32 the num is a runtime argument right? how does it get evaluated at comptime?

It’s runtime information so it can’t rule out that branch at compile time. You are correct.