What\'s the difference between constexpr
and const
?
A const int var
can be dynamically set to a value at runtime and once it is set to that value, it can no longer be changed.
A constexpr int var
cannot be dynamically set at runtime, but rather, at compile time. And once it is set to that value, it can no longer be changed.
Here is a solid example:
int main(int argc, char*argv[]) {
const int p = argc;
// p = 69; // cannot change p because it is a const
// constexpr int q = argc; // cannot be, bcoz argc cannot be computed at compile time
constexpr int r = 2^3; // this works!
// r = 42; // same as const too, it cannot be changed
}
The snippet above compiles fine and I have commented out those that cause it to error.
The key notions here to take note of, are the notions of compile time
and run time
. New innovations have been introduced into C++ intended to as much as possible ** know **
certain things at compilation time to improve performance at runtime.
Any attempt of explanation which does not involve the two key notions above, is hallucination.