C++ Tutorial

C++ Const

const means this name will not change. The compiler enforces it.

A name that must stay put

Write const before a type when that name should not be assigned again. The compiler treats a later write as an error. You get the mistake at compile time, not as a wrong answer after the program runs.

Use it for values that are facts in this program: a maximum score, a tax rate, a label you print in several places. If you need to change it, it is not const. Leave the keyword off and use a plain variable.

const variables

Initialize a const on the same line you declare it. There is no later chance to fill it in. After that, you may read it as often as you like.

Example

#include <iostream>
using namespace std;

int main() {
  const int max_score = 100;
  int score = 88;
  cout << score << " / " << max_score << endl;
  return 0;
}

max_score = 50; after the declaration does not compile. That is the feature. If the number must change, drop const.

Why bother for a local int

For one integer in main, const looks optional. It pays off when the same name is used in several functions, or when a future edit might overwrite a limit by accident. Readers also see the intent: this is a fixed rule, not a running total.

Array sizes in this tutorial are compile-time constants. A const int used as a length is easier to change in one place than a magic 4 copied into a declaration and a loop bound.

Example

#include <iostream>
using namespace std;

int main() {
  const int n = 4;
  int scores[n] = {88, 91, 74, 95};
  int total = 0;
  for (int i = 0; i < n; i++) {
    total += scores[i];
  }
  cout << total << endl;
  return 0;
}

const references as parameters

Pass by reference avoids a copy. Pass by const reference also promises the function will not assign through that name. The caller can pass an existing object without fear that the function will overwrite it.

This is the usual way to pass a string or a vector you only need to read. A copy would work and waste work. A plain vector<int>& would let the function callpush_back on the caller's vector. const vector<int>& forbids that.

Example

#include <iostream>
#include <vector>
using namespace std;

int sum_of(const vector<int>& nums) {
  int total = 0;
  for (int n : nums) {
    total += n;
  }
  return total;
}

int main() {
  vector<int> nums = {3, 8, 4};
  cout << sum_of(nums) << endl;
  cout << nums.size() << endl;
  return 0;
}

Open /cpp/try and try nums.push_back(1); inside sum_of. g++ rejects it because nums is a const reference. The size printed in main stays 3.

const methods

A method marked const after its parameter list promises not to change the object. It may read fields and return them. It may not assign to them. Getters are the usual place for this.

The compiler enforces the promise. If get tried n = 0;, the class would not compile. Callers who only have a const object (or a const reference to one) can still call const methods.

Example

#include <iostream>
using namespace std;

class Box {
  int n;
public:
  Box(int n_in) : n(n_in) {}
  int get() const { return n; }
  void set(int n_in) { n = n_in; }
};

int main() {
  Box b(7);
  cout << b.get() << endl;
  b.set(11);
  cout << b.get() << endl;
  return 0;
}

What const does not mean

const is not the same as a preprocessor #define. It is a typed name the compiler checks. It is also not a claim that the whole program is frozen: other variables can still change. Only that name is locked.

WriteMeaning
const int n = 3;This integer will not be reassigned.
const vector<int>& vThis parameter will not modify the caller's vector.
int get() constThis method will not modify the object.

Mark what you only read

Start with const variables for fixed numbers, then const references for objects you pass in to inspect, then const on methods that only report state. Next: namespaces, which keep those names from colliding with someone else's n or get.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

Light-travel distance

In vacuum, distance is c t. In 1.5 s, light goes about 4.50×10⁸ m, a bit more than the Earth–Moon distance (which is ~3.84×10⁸ m). const double c is the speed of light in this file, not a loop index.

s = c t

Example

#include <iostream>
using namespace std;

int main() {
  const double c = 2.998e8;
  double seconds = 1.5;
  cout << "distance = " << c * seconds << " m" << endl;
  return 0;
}

Maths

Perimeter of a regular hexagon

A regular hexagon has six equal sides. Perimeter is 6 × edge. const int SIDES documents the six and blocks SIDES = 7. For edge 2, P = 12.

P = n × a

Example

#include <iostream>
using namespace std;

int main() {
  const int SIDES = 6;
  double edge = 2.0;
  cout << "perimeter = " << SIDES * edge << endl;
  return 0;
}

FAQ: C++ Const

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ const examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ const in this C++ C++ lesson (C++ Const).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.