Compile-time function execution: Difference between revisions

Content deleted Content added
Minor edit: add space
minor rewording to clarify
Line 1:
'''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 (program lifecycle phase)|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 (is a [[pure function]]).
 
Even ifIf 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.
 
==Examples==
The [[Lisp (programming language)|Lisp]] macro system is an early example of the use of compile-time evaluation of user-defined functions in the same language.
 
In earlier versions of [[C++]], [[template metaprogramming]] is often used to compute values at compile time, such as:
Line 46:
In [[C++11]], this technique is known as [[C++11#constexpr – Generalized constant expressions|generalized constant expressions]] (<code>constexpr</code>).<ref>{{cite web|url=http://www.stroustrup.com/sac10-constexpr.pdf|author=Gabriel Dos Reis and Bjarne Stroustrup | title=General Constant Expressions for System Programming Languages. SAC-2010. The 25th ACM Symposium On Applied Computing. | date=March 2010}}</ref> [[C++14]] [[C++14#Relaxed constexpr restrictions|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).
 
The Metacode extension to C++ (Vandevoorde 2013)<ref>{{cite web|url=http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1471.pdf|title=Reflective Metaprogramming in C++|author=Daveed Vandevoorde, Edison Design Group|date=April 18, 2003|accessdate=July 19, 2015}} </ref> alsowas allowedan early experimental system to allow compile-time function evaluation (CTFE) and code injection as an improved syntax for C++ [[Template metaprogramming|template metaprogramming]].
 
Here's an example of compile time function evaluation (CTFE) in the [[D programming language]]:<ref>[http://d-programming-language.org/function.html#interpretation D 2.0 language specification: Functions]</ref>
 
<source lang="D">