3 ms·
Tbf, Zig allows that too (calling the same function in a runtime and comptime context): fn square(num: i32) i32 { return num * num; } pub
by flohofwoe 2y ago
Tbf, Zig allows that too (calling the same function in a runtime and comptime context):
fn square(num: i32) i32 {
return num * num;
}
pub fn main() void {
_ = square(2);
_ = comptime square(3);
}
...and the comptime invocation will produce a compile error if anything isn't comptime-compatible (which IMHO is an important feature, because it rings the alarm bells if code that's expected to run at comptime accidentially moves into runtime because some input args have changed from comptime- to runtime-evaluated).
- WalterBright 2y agoD does not need the extra keyword. The extra keyword is the same fault that C++ `constexpr` has. It's simply not necessary. The trigger for D is `constant-expression` in the grammar. We have a lot of D users that come from C++, and not one of them has ever asked for `constexpr` that I've heard.
- flohofwoe 2y agoI see the keyword as a feature, not a crutch ;) It guarantees that this area of code will always be evaluated at comptime, and otherwise fail to compile. Compilers (or rather their optimizer passes I guess) already try to fold a lot of code into a constant if it can be evaluated at compile time, but it will silently fall back to runtime evaluation when a variable slips into the code later. With a keyword I can at least say "please fail when that happens".
- WalterBright 2y agoD guarantees that code that is an implementation of a constant-expression is evaluated at compile time. There really is no purpose to adding a keyword.
- drjeats 2y agoIn the most common cases, Zig does exactly what D does here as well. Constant expressions are folded at compile time like any reasonable systems language. It's akin to writing C++ where you slap constexpr on everything. Zig agrees with D that constexpr is silly :) The one thing is Zig doesn't have D's notion of function purity, so I suspect there are cases where D could either infer that an expression is const where Zig can't, or at the very least D's compiler could do it faster. Not to dismiss D's contributions to systems programming languages, of course. Clearly a ton of inspiration of being pulled from y'all's work.