C++ constexpr Keyword.

Article hero image

C++ constexpr Keyword

The constexpr keyword in C++ is used to declare that the value of a variable or the result of a function can be evaluated at compile time. This allows for various optimizations and ensures that certain expressions are constant.

Key Points

  • Compile-Time Evaluation: constexpr enables expressions to be evaluated at compile time, resulting in faster execution time since the values are computed during compilation.
  • Constants: Variables declared with constexpr are implicitly const.
  • Functions: Functions declared with constexpr can produce compile-time constants when called with constant expressions.

Examples

Constexpr Variable

constexpr int max_size = 100;

Constexpr Function

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

Usage in Classes

class MyClass {
public:
    constexpr MyClass(int x) : value(x) {}
    constexpr int getValue() const { return value; }
private:
    int value;
};

int main() {
    constexpr MyClass myObject(10);
    static_assert(myObject.getValue() == 10, "Value should be 10");
}

Important Notes

  • The expression provided to a constexpr variable must be a constant expression.
  • A constexpr constructor allows objects of the class type to be constructed with constant expressions.
  • From C++14 onwards, relaxed restrictions allow more complex computations within constexpr functions, including loops and multiple statements.

Benefits

  • Performance: Compile-time evaluation reduces runtime overhead.
  • Safety: Ensures certain values remain constant throughout the program.
  • Optimization: Facilitates compiler optimizations by providing more information about constants.