const and constexpr in C++
const is a promise the compiler enforces: a const variable cannot be reassigned after initialization, which documents intent and lets the compiler catch accidental mutation. Pass-by-const-reference (const std::string&) is the backbone of efficient, safe C++ interfaces — no copy, no modification.
constexpr goes further, demanding compile-time evaluation: constexpr int SZ = 1024; is computed while compiling, so it can size arrays and drive template arguments. Use const for values fixed at run time, constexpr for values knowable at compile time.
const locks a variable
const int LIMIT = 100; can be read anywhere but never assigned again — any attempt is a compile error.
const references avoid copies safely
void print(const std::string& s) reads a string without copying it and guarantees it won't be modified.
constexpr means compile-time
constexpr values are computed during compilation, so they can size raw arrays and appear in static_assert checks.
constexpr functions
A constexpr function may run at compile time (when given constant arguments) or at run time — one definition serves both.
#include <iostream> constexpr int square(int n) { return n * n; } int main() { const int limit = 10; constexpr int area = square(5); std::cout << limit << ", " << area << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.