5 ms·
This is why I like zig’s comptime concept. It’s essentially the same concept except it’s explicit and you are in control
by pyrolistical 4y ago
This is why I like zig’s comptime concept. It’s essentially the same concept except it’s explicit and you are in control
- varajelle 4y ago'comptime' only works if all arguments are known at compile time and the function can be evaluated at compile time. This is not the same as inlining, which puts the body of the function in the caller and remove the call. (And then do further optimisations such as const propagation)
- chrisaycock 4y agoThe two terms refer to very different phenomena. Consider this incrementing function: int f(int x) {return x + 1;} int main() { int y = f(3); // this will change return 0; } inline means to substitute the body of the function into the call site: int y = 3 + 1; comptime means to substitute the results of the function call into the call site: int y = 4; An inline function only requires that the compiler decide the function body is "small enough" and not recursive. The compiler simply rewrites the AST before codegen. But comptime evaluation means that the compiler has actually run the function ahead of time. (This might be done via a builtin virtual machine, for example.) The requirements are that the function is "pure" (no side effects) and that the inputs can also be resolved ahead of time. A recursive function could be comptime but not inline, whereas a function with IO could be inline but not comptime. The above incrementing function just happens to be both inline and comptime.
- watersb 4y agoThanks for the examples. I gather that zig "comptime" is somewhat like C++11 "constexpr". https://www.hackingnote.com/en/cpp/const-vs-constexpr/index.html https://www.hackingnote.com/en/cpp/const-vs-constexpr/index....
- JonChesterfield 4y agoMinor point, but inlining recursive functions is fine and is done. It's analogous to loop peeling. Inline it once, see if things got better, then decide whether to go again.