Tag: C++, const, constexpr

  • Difference Between const and constexpr in C++

    In C++, const and constexpr are used for defining constant values. The const keyword declares variables that cannot be modified after initialization. However, the value can be determined at runtime. On the other hand, constexpr requires the value to be known at compile time. This leads to optimizations during the compilation phase.

    Here’s a simple illustration:
    “`cpp
    #include
    using namespace std;
    const int a = 5; // can be evaluated at runtime
    constexpr int b = 10; // must be evaluated at compile time
    int main() {
    cout << a << ' ' << b << endl; return 0; } ``` In this example, a is a constant that can be evaluated later. But b must be evaluated during compilation. Using constexpr can enable certain compiler optimizations, improving performance. Use const for variables that may need runtime evaluation. Reserve constexpr for situations needing compile-time constants.