Consteval
   HOME

TheInfoList



OR:

In
computing Computing is any goal-oriented activity requiring, benefiting from, or creating computer, computing machinery. It includes the study and experimentation of algorithmic processes, and the development of both computer hardware, hardware and softw ...
, compile-time function execution (or compile-time function evaluation, or general constant expressions) is the ability of a
compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
, that would normally compile a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
to
machine code In computer programming, machine code is computer code consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). For conventional binary computers, machine code is the binaryOn nonb ...
and
execute Execution, in capital punishment Capital punishment, also known as the death penalty and formerly called judicial homicide, is the state-sanctioned killing of a person as punishment for actual or supposed misconduct. The sentence (law), s ...
it at run time, to execute the function at
compile time In computer science, compile time (or compile-time) describes the time window during which a language's statements are converted into binary instructions for the processor to execute. The term is used as an adjective to describe concepts relat ...
. 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 In computer programming, a pure function is a function that has the following properties: # the function return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference ...
). 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 In computing, partial evaluation is a technique for several different types of program optimization by specialization. The most straightforward application is to produce new programs that run faster than the originals while being guaranteed to ...
), possibly producing more optimized code than if no arguments were known.


Examples


Lisp

The Lisp macro system is an early example of the use of compile-time evaluation of user-defined functions in the same language.


C++

The Metacode extension to C++ (Vandevoorde 2003) was an early experimental system to allow compile-time function evaluation (CTFE) and code injection as an improved syntax for C++
template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these te ...
. In earlier versions of C++,
template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these te ...
is often used to compute values at compile time, such as: template struct Factorial ; template <> struct Factorial<0> ; // Factorial<4>::value

24 // Factorial<0>::value

1 void Foo()
Using compile-time function evaluation, code used to compute the factorial would be similar to what one would write for run-time evaluation e.g. using C++11 constexpr. #include constexpr int Factorial(int n) constexpr int f10 = Factorial(10); int main() In
C++11 C++11 is a version of a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior vers ...
, this technique is known as generalized constant expressions (constexpr).
C++14 C14, C.XIV or C-14 may refer to: Time * The 14th century * Carbon-14, a radioactive isotope of carbon ** Radiocarbon dating, C-14 dating, a method for dating events Science * IEC 60320#C14, IEC 60320 C14, a polarised, three pole socket electrical ...
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). Here's an example of compile-time function evaluation in C++14: // Iterative factorial at compile time. constexpr int Factorial(int n) int main()


Immediate functions (C++)

In
C++20 C20 or C-20 may refer to: Science and technology * Carbon-20 (C-20 or 20C), an isotope of carbon * C20, the smallest possible fullerene (a carbon molecule) * C20 (engineering), a mix of concrete that has a compressive strength of 20 newtons per squ ...
, immediate functions were introduced, and compile-time function execution was made more accessible and flexible with relaxed constexpr restrictions. // Iterative factorial at compile time. consteval int Factorial(int n) int main() Since function Factorial is marked consteval, it is guaranteed to invoke at compile-time without being forced in another manifestly constant-evaluated context. Hence, the usage of immediate functions offers wide uses in metaprogramming, and compile-time checking (used in C++20 text formatting library). Here's an example of using immediate functions in compile-time function execution: void you_see_this_error_because_assertion_fails() consteval void cassert(bool b) consteval void test() int main() 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: In function 'int main()': in 'constexpr' expansion of 'test()' in 'constexpr' expansion of 'cassert(x

12)' error: call to non-'constexpr' function 'you_see_this_error_because_assertion_fails()' you_see_this_error_because_assertion_fails(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~ ...
Here's another example of using immediate functions as constructors which enables compile-time argument checking: #include #include void you_see_this_error_because_the_message_ends_with_exclamation_point() struct checked_message ; void send_calm_message(checked_message arg) int main() The compilation fails here with the message: In function 'int main()': in 'constexpr' expansion of 'checked_message(((const char*)"Hello, world!"))' error: call to non-'constexpr' function 'void you_see_this_error_because_the_message_ends_with_exclamation_point()' you_see_this_error_because_the_message_ends_with_exclamation_point(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~ ...


D

Here's an example of compile-time function evaluation in the
D programming language D, also known as dlang, is a multi-paradigm system programming language created by Walter Bright at Digital Mars and released in 2001. Andrei Alexandrescu joined the design and development effort in 2007. Though it originated as a re-enginee ...
: int factorial(int n) // computed at compile time enum y = factorial(0); //

1 enum x = factorial(4); //

24
This example specifies a valid D function called "factorial" which would typically be evaluated at run time. The use of enum tells the compiler that the initializer for the variables must be computed at compile time. Note that the arguments to the function must be able to be resolved at compile time as well. CTFE can be used to populate data structures at compile-time in a simple way (D version 2): int[] genFactorials(int n) enum factorials = genFactorials(13); void main() // 'factorials' contains at compile-time: // [1, 1, 2, 6, 24, 120, 720, 5_040, 40_320, 362_880, 3_628_800, // 39_916_800, 479_001_600] CTFE can be used to generate strings which are then parsed and compiled as D code in D.


Zig

Here's an example of compile-time function evaluation in the
Zig programming language Zig is an imperative, general-purpose, statically typed, compiled system programming language designed by Andrew Kelley. It is free and open-source software, released under an MIT License. A major goal of the language is to improve on the C l ...
: pub fn factorial(n: usize) usize pub fn main() void This example specifies a valid Zig function called "factorial" which would typically be evaluated at run time. The use of comptime tells the compiler that the initializer for the variables must be computed at compile time. Note that the arguments to the function must be able to be resolved at compile time as well. Zig also support Compile-Time Parameters.Zig 0.11.0 Language Reference: Compile-Time Parameters
/ref> pub fn factorial(comptime n: usize) usize pub fn main() void CTFE can be used to create generic data structures at compile-time: fn List(comptime T: type) type // The generic List data structure can be instantiated by passing in a type: var buffer: 032 = undefined; var list = List(i32);


References


External links


Rosettacode examples of compile-time function evaluation in various languages
{{Compiler optimizations Compiler construction Articles with example C++ code Articles with example D code Compiler optimizations