C++ Constants & Variables Complete Guide
Fundamental Concepts

C++ Constants, Literals, and Variable Rules

Master C++ constants, literals, tokens, and variable rules. Learn about const, constexpr, variable scope, naming conventions, and storage classes with short focused examples.

Constants

const & constexpr

Literals

Numeric & String

Tokens

Keywords & Identifiers

Variables

Rules & Scope

C++ Tutorial · Constants & Variables

Variables store state; constants protect invariants. Master declaration, initialization, const correctness, and scope rules—the foundation of reliable C++ programs.

What you will learn

  • Declare and initialize variables with correct types
  • Use const and constexpr for compile-time safety
  • Compare #define macros vs const/constexpr
  • Apply scope rules: local, global, and block scope
  • Follow naming conventions readable to teams

Why this topic matters

Const correctness is a hallmark of professional C++. Many bugs come from mutable state that should have been const.

Key terms & indexing

C++ constants C++ variables constexpr const C++ C++ literals

1. Constants in C++

Constants are fixed values that cannot be altered during program execution. C++ provides several ways to define constants.

Using const Keyword

The 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";
Using 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 vs constexpr

const indicates "read-only" while constexpr indicates "compile-time constant". All constexpr objects are const, but not all const objects are constexpr.

Simple Examples

1. const int
const int MAX = 50;
// MAX = 60; // error
2. const double
const double TAX = 0.15;
cout << TAX;
3. constexpr (compile-time)
constexpr int N = 100;
constexpr double PI = 3.14159;
4. constexpr function
constexpr int sq(int x) {
    return x * x;
}
5. Pointer to const
int val = 10;
const int* p = &val;
// *p = 20; // error
6. const pointer
int x = 5;
int* const p = &x;
*p = 7; // OK

2. Literals in C++

Literals 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)

Simple Examples

1. Decimal literal
int n = 42;
cout << n;
2. Hex and octal
int hex = 0x2A;  // 42
int oct = 052;     // 42
3. Binary (C++14)
int bin = 0b101010;
cout << bin;
4. Float suffix
float f = 3.14f;
double d = 3.14159;
5. Character literal
char c = 'A';
char nl = '\n';
6. Raw string (C++11)
string s = R"(Line1\nLine2)";
cout << s;
Literal Suffixes: Use 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).

3. Tokens in C++

Tokens are the smallest individual elements in a C++ program. The compiler breaks code into tokens during compilation.

Keywords

Reserved words with special meaning. Cannot be used as identifiers.

int, float, double
if, else, switch
for, while, do
class, struct, enum
const, static, auto
public, private
Identifiers

Names given to variables, functions, classes, etc. Must follow naming rules.

Valid:
myVariable
calculateArea
MAX_SIZE
Invalid:
123var
my-var
float
Identifier Naming Rules:
  1. Can contain letters (a-z, A-Z), digits (0-9), and underscores (_)
  2. Must begin with a letter or underscore (not a digit)
  3. Cannot be a C++ keyword
  4. Case-sensitive (myVarMyVar)
  5. No special characters except underscore
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 ;, ,, ., :, {}, [], ()

4. Variable Rules and Scope

Variables are named storage locations. Understanding variable rules, scope, and lifetime is essential for writing correct C++ programs.

Variable Declaration and Initialization

Simple Examples

1. Declare and initialize
int score = 95;
cout << score;
2. Multiple variables
int x = 5, y = 10, z = 15;
cout << x + y + z;
3. auto inference
auto price = 99.99;  // double
auto ok = true;        // bool
4. decltype
int val = 42;
decltype(val) copy = val;
5. Reference alias
int n = 50;
int& ref = n;
ref = 60; // n is 60
6. const reference
int n = 10;
const int& r = n;
cout << r;

Variable Scope

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

Storage Classes

auto (default)

Default for local variables. Automatic storage duration.

auto int x; (obsolete)
auto y = 5; (C++11 type inference)
static

Retains value between function calls. Lifetime: entire program.

static int counter = 0;
Preserves value across calls
extern

Declares variable defined elsewhere. Used for sharing between files.

extern int globalVar;
Defined in another file
register

Hint to store in register (largely obsolete with modern compilers).

register int fast;
Compiler may ignore
Common Mistakes:
  • Using uninitialized variables (contains garbage values)
  • Scope confusion (accessing variables outside their scope)
  • Name shadowing (local variable hides global variable with same name)
  • Forgetting to free dynamically allocated memory
  • Using dangling references or pointers

5. Best Practices

Do's
  • Use const for values that shouldn't change
  • Use constexpr for compile-time constants
  • Initialize variables when declaring them
  • Use meaningful, descriptive names
  • Follow naming conventions (camelCase, PascalCase, UPPER_CASE)
  • Limit variable scope as much as possible
  • Use auto when type is obvious from initialization
Don'ts
  • Don't use global variables unnecessarily
  • Don't use magic numbers (use named constants)
  • Don't use single-letter names except for counters
  • Don't declare all variables at the top (old C style)
  • Don't use register keyword (obsolete)
  • Don't use Hungarian notation in modern C++
  • Don't use #define for constants (use const)

Naming Convention Examples

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.

Simple Examples

1. UPPER_CASE constant
constexpr int MAX = 50;
cout << MAX;
2. camelCase variable
int studentCount = 0;
studentCount++;
3. Block scope
{
    int temp = 42;
    cout << temp;
} // temp destroyed
4. const ref (no copy)
string name = "Ali";
const auto& ref = name;
5. static counter
static int count = 0;
count++; // keeps value
6. Circle area helper
constexpr double PI = 3.14159;
double area = PI * 5.5 * 5.5;

Frequently asked questions

What is the difference between const and constexpr?

const means read-only; constexpr requires a compile-time constant expression when used for constants.

Should I use #define for constants?

Prefer const or constexpr in modern C++—they are type-safe and respect scope.

Can constants be changed at runtime?

No. const objects cannot be assigned new values after initialization.