C++ Language & Safety
const, constexpr & volatile
Read-only vs compile-time-known vs don't-optimize.
Concept core idea Watch out easy to get wrong
Concept
Key concepts
const= won't change after initialization (but CAN be set at runtime).constexpr= value/function evaluable at compile time (stronger). Everyconstexprisconst, not vice versa.constexprfunction: runs at compile time with compile-time args, else at runtime.volatile= don't optimize accesses; re-read from memory every time (value may change externally). Not for thread sync — usestd::atomic.
const vs constexpr
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.