Constexpr Function in C++

Level 5283 keystrokes

A constexpr factorial function is evaluated at compile time when its result initializes a constexpr variable, and can also be called like an ordinary function. It prints 120, 5040 and 720.

C++ code

// constexpr: can be evaluated at compile time when the argument is a constant
1constexpr int factorial(int n) {
// Recursion: n! = n × (n - 1)!, and 1 when n <= 1
2 return (n <= 1) ? 1 : n * factorial(n - 1);
3}
4
// A constexpr variable forces evaluation at compile time: 120
5constexpr int compiletime = factorial(5);
// Ordinary variable: the same function also works like a normal call (5040)
6int runtime = factorial(7);
7
// Prints "Compile-time: 120"
8cout << "Compile-time: " << compiletime << endl;
// Prints "Runtime: 5040"
9cout << "Runtime: " << runtime << endl;
// Called directly inside the expression: 6! = 720
10cout << "Direct: " << factorial(6) << endl;

Output

Compile-time: 120
Runtime: 5040
Direct: 720
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 19
  • ;× 6
  • "× 6
  • (× 6
  • )× 6
  • :× 4
  • =× 3
  • -× 2
  • ?× 1
  • {× 1

More C++ examples at level 5

← C++ typing practice