Sobes.tech
Junior — Middle

What is the purpose of the constexpr keyword in C++ and how is it used?

sobes.tech AI

Answer from AI

The keyword constexpr in C++ is used to indicate that a function or variable can be evaluated at compile time. This helps improve performance and safety, as calculations are performed in advance.

Key points of using constexpr:

  • constexpr functions must contain only expressions that can be evaluated during compilation.
  • Such functions can be used to initialize constant expressions, for example, in array or template definitions.
  • Starting with C++14, constexpr functions can include more complex constructs, including loops and branches.

Example:

constexpr int factorial(int n) {
    return n <= 1 ? 1 : (n * factorial(n - 1));
}

int arr[factorial(5)]; // array size computed at compile time

Thus, constexpr helps create more efficient and safer code by enabling computations at compile time.

What is the purpose of the constexpr keyword in C++… - sobes.tech