What\'s the difference between constexpr
and const
?
As @0x499602d2 already pointed out, const
only ensures that a value cannot be changed after initialization where as constexpr
(introduced in C++11) guarantees the variable is a compile time constant.
Consider the following example(from LearnCpp.com):
cout << "Enter your age: ";
int age;
cin >> age;
const int myAge{age}; // works
constexpr int someAge{age}; // error: age can only be resolved at runtime