The difference between const&constexpr objects in C++

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()
    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.