| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Compile-time_function_execution |
| Contents |
|---|
| D |
| Zig |
| References |
In computing, compile-time function execution (or compile-time function evaluation, or general constant expressions) is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the function at compile time. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state (i.e. it is a pure function).
If the value of only some of the arguments are known, the compiler may still be able to perform some level of compile-time function execution (partial evaluation), possibly producing more optimized code than if no arguments were known.
importstd; constexprunsignedintfactorial(unsignedintn)noexcept{ returnn?(n*factorial(n-1)):1; } constexprunsignedintf10=factorial(10); intmain(){ std::println("{}",f10); return0; }In C++11, this technique is known as generalized constant expressions (constexpr). C++14 relaxes the constraints on constexpr, allowing local declarations and use of conditionals and loops (the general restriction that all data required for the execution be available at compile-time remains).
In C++20, immediate functions were introduced with the voidassertionFailed(){} constevalvoidtestAssert(boolcond){ if(!cond){ assertionFailed(); } } constevalvoidtest(){ intx=10; testAssert(x==10);// ok x++; testAssert(x==11);// ok x--; testAssert(x==12);// fails here } intmain(){ test(); }
In this example, the compilation fails because the immediate function invoked function which is not usable in constant expressions. In other words, the compilation stops after failed assertion.
The typical compilation error message would display:
This is an example of compile-time function evaluation in the D programming language:
This is an example of compile-time function evaluation in Zig.
| View original on Wikipedia | Back | FazBrowse Home |