const vs constexpr.

When to use const and when to use constexpr? What’s the difference between them?

I believe constexpr is initialized during compile time, so it can be used in situations where a compile time constant is needed. Const can be initialized during compile time or runtime.

A good way to figure that out is to try to set a static array’s size using a variable declared as const or constexpr. A const is a constant expression provided that it is initialized with a constant expression, an integer literal for instance. The problem with const is that it can be initialized at run-time and won’t warn you if you assign it to any function that isn’t a constant expression, what I mean by that is


    const int i = ceil(1024);
    int Array* = {1,2,2,3,3,4,4};

Here you’ll only get an error because i is being set as the array’s size. Whereas if a constexpr was used, it would complain right at the initialization phase. One thing to note however is that a function can also be executed at compile-time so long as its declared constexpr, but there are rules - your compiler should give you a warning if the function will be executed at compile time.


template<typename T>
constexpr T Max(T a, T b)
{
    return a < b ? b : a;
}

int main()
{
    int a = 1, b = 2;
    Max(a, b);
}

For instance in the case above, Max ought to be executed at run-time, the two local variables are passed to registers and pushed on the stack then the call to Max follows. On the other hand if you’d have passed 1 and 2.


template<typename T>
constexpr T Max(T a, T b)
{
    return a < b ? b : a;
}

int main()
{
    int a = 1, b = 2;
    Max(1,2);
}

and check the dissassembly output, then you probably wouldn’t have seen much, and the function should be executed at compile-time. :slight_smile: