In C++
, const
object means once initialized, its value can’t be changed. The initialization can occur in compile-time:
const auto c = 0;
Or in run-time:
#include <cstdlib>
#include <ctime>
auto func()
{
return std::rand() % 10;
}
int main()
{
std::srand(std::time(0));
const auto c = func();
return 0;
}
For constexpr
objects, you can think they are a subset of const
objects, and the constexpr
object’s value must be determined in compile-time. Change the declaration of c
in above code:
constexpr auto c = func();
The code can’t be compiled because the c
‘s value couldn’t be generated during compilation phrase.