0Pricing
C++ Academy · Lesson

const Variables and Parameters

Protect data from change.

Declaring const Variables

A const variable cannot be modified after initialization. The compiler enforces this, catching accidental writes.

#include <iostream>

int main() {
    const int maxUsers = 100;
    // maxUsers = 200;   // ERROR
    std::cout << maxUsers << "\n";
}

const Function Parameters

Marking a by-value parameter const prevents the function body from altering its local copy — a documentation and safety aid.

#include <iostream>

int doubled(const int n) {
    // n = 0;   // ERROR
    return n * 2;
}

int main() { std::cout << doubled(21) << "\n"; }

All lessons in this course

  1. const Variables and Parameters
  2. const Member Functions
  3. constexpr and Compile-Time
  4. consteval and constinit
← Back to C++ Academy