01 / 21

Using const
in C++

Master the const keyword to write safer, more expressive code by protecting values from accidental modification.

C++

What is const?

The const keyword tells the compiler that a value must not be modified after initialization. It is a compile-time promise of immutability: the compiler enforces the restriction and reports any violation as an error.

Why const Matters

Safety
Prevents accidental overwrites of values that should never change.
Readability
Signals to other programmers that a value is intentionally fixed.
Optimization
Gives the compiler freedom to optimize because it knows the value won't change.

const Variables: The Basics

// Declaring a const variable const int maxScore = 100; const double pi = 3.14159265; const std::string greeting = "Hello"; // ERROR: cannot modify a const variable maxScore = 200; // compile error!

The Core Rule of const

DECLARATION const int x = 42; Initialized ✓ LOCKED Value is 42 forever MODIFICATION x = 99; Blocked ✕ COMPILE ERROR assignment of read-only

const with References

int value = 42; const int& ref = value; std::cout << ref; // OK: reading through ref ref = 99; // ERROR: ref is const value = 99; // OK: value itself isn't const

const with Pointers

Pointer to const const int* ptr; Can't change *ptr Can change ptr itself const Pointer int* const ptr; Can change *ptr Can't change ptr itself const Pointer to const const int* const ptr; Can't change *ptr Can't change ptr itself

const vs constexpr

const constexpr
Evaluated at Runtime or compile time Always compile time
Initialization Can use runtime values Must use compile-time values
Use case Any immutable value True compile-time constants
Example const int n = getN(); constexpr int n = 42;

const in Function Parameters

// Pass by const reference: efficient + safe void print(const std::string& msg) { std::cout << msg; // msg = "oops"; // ERROR: msg is const } // Pass by value: const prevents local modification int square(const int n) { return n * n; }

const Member Functions

class Circle { double radius; public: Circle(double r) : radius(r) {} // const member function: won't modify the object double area() const { return 3.14159 * radius * radius; } // non-const: modifies the object void setRadius(double r) { radius = r; } };

How to Apply const

1
Start with const. Declare every variable and parameter as const by default.
2
Check if mutation is needed. Only remove const when the value genuinely must change.
3
Prefer const references. For function parameters of class types, use const T& over plain T.
4
Mark member functions. If a method only reads member data, append const after the parameter list.
5
Compile and fix. If the compiler flags a const violation, decide: should the variable be mutable, or is the modification a bug?

Example 1: Simple Constants

const int MAX_STUDENTS = 30; const double TAX_RATE = 0.08; double calculateTax(const double price) { return price * TAX_RATE; } int main() { double total = calculateTax(49.99); // total = 3.9992 }

Example 2: const Reference Parameters

#include <vector> #include <string> void printAll(const std::vector<std::string>& names) { for (const auto& name : names) { std::cout << name << "\n"; } // names.push_back("X"); // ERROR: names is const }

Example 3: Pointer Constness

int a = 10, b = 20; // Pointer to const: can't change the pointed-to value const int* p1 = &a; *p1 = 99; // ERROR p1 = &b; // OK: pointer itself can move // const pointer: can't re-point, but can change value int* const p2 = &a; *p2 = 99; // OK: can change *p2 p2 = &b; // ERROR: p2 is const

Common Mistakes

✕ Forgetting to Initialize
Writing const int x; without an initializer causes a compile error. Every const must be initialized.
✕ Mixing Up Pointer Const
Confusing const int* (pointer to const) with int* const (const pointer). Read right-to-left.
✕ Passing Large Objects by Value
Using const std::string s when you should use const std::string& s. Pass by const reference for efficiency.

const Quick Reference

Syntax Meaning Can Modify?
const int x = 5; Immutable variable No
const int& ref = x; Immutable reference Not through ref
const int* ptr; Pointer to const ptr: yes, *ptr: no
int* const ptr; const pointer ptr: no, *ptr: yes
void f() const; const member function No members

Question 1 of 5

Which declaration will cause a compile error?

Question 2 of 5

Given const int* ptr, which operation is allowed?

Question 3 of 5

What does placing const after a member function's parameter list do?

Question 4 of 5

Why should you prefer const std::string& over const std::string as a function parameter?

Question 5 of 5

What is the key difference between const and constexpr?