What is the difference between const and constexpr?
const means read-only; constexpr requires a compile-time constant expression when used for constants.
Master C++ constants, literals, tokens, and variable rules. Learn about const, constexpr, variable scope, naming conventions, and storage classes with short focused examples.
const & constexpr
Numeric & String
Keywords & Identifiers
Rules & Scope
Variables store state; constants protect invariants. Master declaration, initialization, const correctness, and scope rules—the foundation of reliable C++ programs.
Const correctness is a hallmark of professional C++. Many bugs come from mutable state that should have been const.
Constants are fixed values that cannot be altered during program execution. C++ provides several ways to define constants.
const KeywordThe const keyword specifies that a variable's value is constant and tells the compiler to prevent modification.
const int MAX_SIZE = 100;
const double PI = 3.14159;
const std::string GREETING = "Hello";
constexpr (C++11)constexpr specifies that the value is constant and can be evaluated at compile-time.
constexpr int ARRAY_SIZE = 100;
constexpr double EULER = 2.71828;
constexpr int SQUARE(int x) { return x * x; }
const indicates "read-only" while constexpr indicates "compile-time constant". All constexpr objects are const, but not all const objects are constexpr.
const int MAX = 50;
// MAX = 60; // errorconst double TAX = 0.15;
cout << TAX;constexpr int N = 100;
constexpr double PI = 3.14159;constexpr int sq(int x) {
return x * x;
}int val = 10;
const int* p = &val;
// *p = 20; // errorint x = 5;
int* const p = &x;
*p = 7; // OKLiterals are constant values used directly in the code. They can be of various types including integer, floating-point, character, and string literals.
| Literal Type | Description | Examples |
|---|---|---|
| Integer Literals | Whole numbers without fractional part | 42, 0xFF, 075, 0b1010 |
| Floating-point | Numbers with decimal point or exponent | 3.14, 2.5e-3, 1.0f |
| Character Literals | Single character enclosed in single quotes | 'A', '\n', '\x41', '\u0041' |
| String Literals | Sequence of characters in double quotes | "Hello", "C++\n", R"(Raw String)" |
| Boolean Literals | Logical true/false values | true, false |
| Null Pointer | Pointer that doesn't point to anything | nullptr (C++11) |
int n = 42;
cout << n;int hex = 0x2A; // 42
int oct = 052; // 42int bin = 0b101010;
cout << bin;float f = 3.14f;
double d = 3.14159;char c = 'A';
char nl = '\n';string s = R"(Line1\nLine2)";
cout << s;U for unsigned, L for long, LL for long long, F for float, and L for long double. Example: 100UL (unsigned long), 3.14F (float).
Tokens are the smallest individual elements in a C++ program. The compiler breaks code into tokens during compilation.
Reserved words with special meaning. Cannot be used as identifiers.
int, float, doubleif, else, switchfor, while, do
class, struct, enumconst, static, autopublic, private
Names given to variables, functions, classes, etc. Must follow naming rules.
myVariablecalculateAreaMAX_SIZE
123varmy-varfloat
myVar ≠ MyVar)| Token Type | Description | Examples |
|---|---|---|
| Keywords | Predefined reserved words | int, class, return, if, for |
| Identifiers | Names defined by programmer | variableName, calculateTotal, Student |
| Constants/Literals | Fixed values | 100, 3.14, 'A', "Hello" |
| Operators | Symbols that perform operations | +, -, *, /, =, ==, &, -> |
| Punctuators | Syntax elements | ;, ,, ., :, {}, [], () |
Variables are named storage locations. Understanding variable rules, scope, and lifetime is essential for writing correct C++ programs.
int score = 95;
cout << score;int x = 5, y = 10, z = 15;
cout << x + y + z;auto price = 99.99; // double
auto ok = true; // boolint val = 42;
decltype(val) copy = val;int n = 50;
int& ref = n;
ref = 60; // n is 60int n = 10;
const int& r = n;
cout << r;| Scope Type | Description | Example & Lifetime |
|---|---|---|
| Local Scope | Declared inside a function or block. Accessible only within that block. | void func() { int x = 5; }Lifetime: Block execution |
| Global Scope | Declared outside all functions. Accessible throughout the file. | int global = 10;Lifetime: Entire program |
| Function Parameter | Declared in function parameter list. Local to the function. | void print(int num) { ... }Lifetime: Function execution |
| Class Scope | Declared inside a class. Access depends on access specifier. | class MyClass { int data; };Lifetime: Object lifetime |
| Namespace Scope | Declared inside a namespace. Access using namespace qualification. | namespace MyNS { int value; }Lifetime: Program |
Default for local variables. Automatic storage duration.
auto int x; (obsolete)auto y = 5; (C++11 type inference)
Retains value between function calls. Lifetime: entire program.
static int counter = 0;Declares variable defined elsewhere. Used for sharing between files.
extern int globalVar;Hint to store in register (largely obsolete with modern compilers).
register int fast;const for values that shouldn't changeconstexpr for compile-time constantsauto when type is obvious from initializationregister keyword (obsolete)#define for constants (use const)
camelCase: studentName, calculateAverage
PascalCase: StudentName, CalculateAverage (classes, functions)
snake_case: student_name, calculate_average
UPPER_CASE: MAX_SIZE, PI_VALUE (constants)
Choose one style and be consistent throughout your project.
constexpr int MAX = 50;
cout << MAX;int studentCount = 0;
studentCount++;{
int temp = 42;
cout << temp;
} // temp destroyedstring name = "Ali";
const auto& ref = name;static int count = 0;
count++; // keeps valueconstexpr double PI = 3.14159;
double area = PI * 5.5 * 5.5;const means read-only; constexpr requires a compile-time constant expression when used for constants.
Prefer const or constexpr in modern C++—they are type-safe and respect scope.
No. const objects cannot be assigned new values after initialization.