C++ - const vs constexpr vs consteval vs constinit

Updated: 2021-05-13

TL;DR

  • const: declares an object as constant, i.e. once initialized, the value won't change.
    • runtime constant
    • can only be used for non-static member functions, not functions in general.
  • constexpr: Since C++11
    • compile-time constant
    • can be used for both variables and functions
    • All constexpr variables are const
  • consteval: Since C++20,
    • shall be applied only to the declaration of a function or function template
    • A consteval function is guaranteed to be evaluated at compile time.
  • constinit: Since C++20, asserts that a variable has static initialization (zero initialization or constant initialization)

const

Read-only, but not Immutable or always the same

A const object is read-only but this does not imply that it is immutable nor does it imply that the value is always the same.

void f(const std::string& s) {
  const int size = s.size();
  // ...
}

f("");  // size = 0
f("foo");  // size = 3

Other ways to change a const: mutable keyword and const_cast

Where to use const

TL;DR: const applies to the thing left of it, if there's nothing on the left, then it applies to the thing right of it

  • const int *: nothing on the left, so const if for int: a pointer to a constant integer. equivalent to int const *
  • int* const: a constant pointer to an integer, the pointer cannot point to other address, the content can be changed
  • const int* const: a constant pointer to a constant integer, both content and the address are read-only, equivalent to int const * const
  • int const* const *: a pointer to a const pointer to a constant integer
  • int const * const * const: a constant pointer to a constnat pointer to a constant integer

constexpr

constexpr = constant expression

It can be applied to:

  • variables: compile time constants.
  • function: if takes no arguments will always return the same value constexpr int Foo() { return 42; }

Define variables constexpr in .cc files or declare them extern const in .h files.

All constexpr functions are implicitly inline: a constexpr function is just an inline function that is allowed to execute at compile time when initializing constant values.

In Other languages

const keyword is used in other languages, but its meaning may be different. Read more in Programming Languages - Constants