Learn C++
#include "variablesdatatypes/const_constexpr.hpp"

const and constexpr in C++

//concept

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.

//how it works
1

const locks a variable

const int LIMIT = 100; can be read anywhere but never assigned again — any attempt is a compile error.

2

const references avoid copies safely

void print(const std::string& s) reads a string without copying it and guarantees it won't be modified.

3

constexpr means compile-time

constexpr values are computed during compilation, so they can size raw arrays and appear in static_assert checks.

4

constexpr functions

A constexpr function may run at compile time (when given constant arguments) or at run time — one definition serves both.

//example
#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;
}
Output
10, 25
1const int limit = 10; fixes limit at run time — readable everywhere, assignable nowhere.
2square is constexpr, and square(5) with a constant argument evaluates during compilation to 25.
3Both print normally; the difference is invisible at run time but enforced (const) or computed (constexpr) by the compiler.
//use cases
Marking function parameters const& to prevent accidental mutation of caller data
Sizing static buffers and lookup tables with constexpr instead of magic numbers
static_assert testing constants and type properties at compile time, failing the build early
Designing APIs where const-correctness tells callers exactly what a function may change

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.