Some programming languages allow calculation of values at compile time. For this task, calculate 10! at compile time. Print the result when the program is run.
This is called Template metaprogramming. In fact, templates in C++ are Turing-complete, making deciding whether a program will compile undecidable.
Compile-time calculations in C++ look quite different from normal code. We can only use templates, type definitions and a subset of integer arithmetic. It is not possible to use iteration. C++ compile-time programs are similar to programs in pure functional programming languages, albeit with a peculiar syntax.
Alternative version, using constexpr in C++11:
The asm produced by G++ 4.6.0 32 bit (-std=c++0x -S), shows the computation is done at compile-time:
_main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $16, %esp call ___main movl $3628800, 4(%esp) movl $LC0, (%esp) call _printf movl $0, %eax leave ret
Content is available under GNU Free Documentation License 1.2.