We can make a variable unchangeable by defining the variable’s type as const

  • because of its unchangebility, it must initialized
    • the initializer may be an arbitrarily complicated expression
  • 能用的 operations 只有那些其对应 nonconst version 中,不改变该const 的值的操作。
  • const variable 被定义为只有在当前文件,所以 extern 的方法也有点不一样Use in Other File

Top-Level const

We use the term top-level const to indicate that the pointer itself is a const.
When a pointer can point to a const object, we refer to that const as a low-level const.

⚠️ when copy, top-level are ignored but low-level never

constexpr and Constant Expressions

Constant Expressions

A constant expression is an expression whose value cannot change and that can be evaluated at compile time.

a literal is a const expression, a const object initialized by const expression is alse a constexpression.

constexpr Qualifier

like const, but this meas the variable is a constant expression.

Additionally, constexpr imposes a top-level const on the objects it defines.

Pointers and constexpr

constexpr int *q = nullptr;    // q is a const pointer to int