3 ms·
The 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
by chrisaycock 4y ago
The 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.