Variables & Constants
Overview
At its core, a computer program is just an engine that manipulates data. Variables are named memory locations in your RAM where you can store, update, and retrieve this data.
However, in large software engineering projects, data mutation (variables changing unexpectedly) is the number one cause of bugs. C++ strongly encourages the use of 'Constants'—variables that are locked and physically cannot be changed after they are created. C++ provides two levels of constants: const (which guarantees the value won't change after runtime initialization) and constexpr (which forces the compiler to calculate the value during compilation, completely eliminating runtime calculation cost).
Syntax
// 1. A standard mutable variable
int score = 10;
score = 20; // Allowed!
// 2. A runtime constant
// (Can be assigned dynamically when the program runs, but never changed again)
const double PI = 3.14159;
// 3. A compile-time constant (Modern C++)
// (The math '100 * 5' is done during compilation, saving CPU cycles at runtime)
constexpr int MAX_USERS = 100 * 5;Common Pitfalls
- Failing to initialize a
constvariable. Writingconst int x; x = 5;is a fatal compilation error. Constants must be assigned their value at the exact moment they are declared. - Using uninitialized variables. If you write
int health; cout << health;, C++ will NOT default it to 0. It will print whatever garbage data happened to be left in that RAM sector by the last program that used it.
Interview Questions
const and constexpr in modern C++.const signifies that a variable's value cannot be modified after it is initialized, but that initialization can happen dynamically at runtime (e.g., const int input = getUserInput();). constexpr is much stricter; it guarantees that the value is entirely evaluated and hardcoded during compilation, resulting in zero runtime overhead.
Const correctness is the discipline of declaring every variable, function parameter, and class method as const unless it strictly needs to be mutated. It prevents accidental bugs, documents intent, and gives the compiler aggressive optimization opportunities.
Real-World Example
Using compile-time constants to avoid 'Magic Numbers' in business logic.
#include <iostream>
int main() {
// Magic numbers (like 0.08) scattered in code are impossible to maintain.
// Instead, define them as strict compile-time constants!
constexpr double TAX_RATE = 0.08;
double cartTotal = 50.0;
double finalPrice = cartTotal + (cartTotal * TAX_RATE);
std::cout << "Total: $" << finalPrice << "\n";
return 0;
}Check Your Knowledge
Test your understanding of Variables & Constants with these quick questions.