Compile-time function execution: Difference between revisions

Content deleted Content added
RileyBot (talk | contribs)
m Bot: Correcting capitalization or standardizing section headings) (Task 16
Add a C++14 example.
Tag: Newer user possibly adding unreferenced or improperly referenced material
Line 47:
 
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).
 
Here's an example of compile time function evaluation in C++14:
 
<source lang="CPP">
// iterative factorial at compile time
constexpr int factorial(int n) {
int result = n;
while(n > 1)
result *= --n;
return result;
}
main() {
const int f4 = factorial(4); // f4 == 24
}
</source>
 
Here's an example of compile time function evaluation in the [[D programming language]]:<ref>[http://d-programming-language.org/function.html#interpretation D 2.0 language specification: Functions]</ref>