Could we put const at the top of the file and why constexpr?

This is incorrect. constexpr means that the variable/function can be evaluated at compile time, it’s not guaranteed that it necessarily will be.

Similarly const doesn’t mean it will be evaluated at run-time.

const int val = 5 * 5;

is a constant expression and val would be 25 and no calculation of 5*5 would be done at run-time. Compiler Explorer

Also incorrect. Compiler Explorer. It’s the same if you enable optimisations or not. These examples are too trivial for the compiler.


So constexpr for a variable means that it can be evaluated at compile time and is implied to be const.

#include <array>
int square(int n) { return n * n; }
int main()
{
    //compiler error, square is a non-constexpr function.
    constexpr int val = square(5); 
    //okay so far
    const int val2 = square(3);
    //error test was initialised with a non-constexpr value
    std::array<int, val2> test;
}
  • val is a compile time error as it’s marked as constexpr but it’s calling a non-constexpr function.
  • val2 is fine, it’s a const int and initialised to square(3) however it’s then used in an expression where only compile-time constants can be used (template argument) so test is a compile time error.

Making square constexpr will resolve both issues.

2 Likes