Systems CourseC/C++ · Linux · Memory
C++ Language & SafetyLesson 16 of 441 min read6 questions

const, constexpr & volatile

Read-only vs compile-time-known vs don't-optimize.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. const = won't change after initialization (but CAN be set at runtime).
  2. constexpr = value/function evaluable at compile time (stronger). Every constexpr is const, not vice versa.
  3. constexpr function: runs at compile time with compile-time args, else at runtime.
  4. volatile = don't optimize accesses; re-read from memory every time (value may change externally). Not for thread sync — use std::atomic.

const vs constexpr

C++
int n = getInput();
const int a = n;       // OK: const, value known at RUNTIME
constexpr int b = n;   // ERROR: n not a compile-time constant
constexpr int c = 42;  // OK
Watch out

Easily confused

const vs constexpr
const = read-only (may be set at runtime). constexpr = computed by the compiler before the program runs.
constexpr vs volatile
Opposite ends: constexpr pushes work to compile time; volatile forbids optimization and forces runtime re-reads.
volatile vs atomic
volatile = re-read from memory, no thread guarantees. std::atomic = actual thread-safe atomicity/ordering.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.