devnotes.

auto, const, and constexpr

C++11 introduced auto for type inference, and C++ has long distinguished between run-time constants (const) and compile-time constants (constexpr).

auto x = 5;             // inferred as int
auto y = 3.14;          // inferred as double
auto name = std::string("Rahim"); // inferred as std::string

const int maxRetries = 3;      // fixed value, but not necessarily known at compile time
constexpr int bufferSize = 256; // guaranteed evaluated at compile time

constexpr int square(int n) {   // can run at compile time when given a constant argument
    return n * n;
}
constexpr int result = square(5); // computed by the compiler, not at runtime

auto deduces a variable's type from its initializer, reducing repetition — especially valuable with long, verbose types like STL iterators (std::vector<int>::iterator it = ... versus auto it = ...). It requires an initializer (auto x; alone is a compile error, since there's nothing to infer from), and most style guides recommend it primarily when the type is either obvious from context or genuinely unwieldy to spell out.

const promises a value won't change after initialization, but its value can still come from something only known at run time (e.g., const int userInput = readFromFile();). constexpr is stronger: it requires the value to be computable at compile time, which lets the compiler use it in contexts requiring a compile-time constant (like array sizes) and, when possible, evaluate whole functions during compilation rather than at runtime — as with square(5) above, which the compiler can fold into the literal 25 before the program even runs.

auto, const, and constexpr in C++ | DevNotes