A Bit about const

A brief introduction of the 'const' keyword and how it can be used.

We'll cover the following

The const keyword specifies that a value is “constant” and cannot be changed after it’s initially set. This is useful because it can reduce the complexity of our program by reducing how many elements can change in the program environment. However, we also have to be careful when using const variables because we cannot reverse our const specification.

If we can make something const, we should make it const. That is the least we can do for our compiler.

Many senior C++ developers give the above advice to junior developers, but often fail to follow it themselves!

It is very easy to declare a variable without making it const, we know that its value should never change. However, our compiler doesn’t know that.

The compiler cannot think, after all, at least not for the time being.

Compilation errors are easy to spot early on, but dangling references or degrading performance due to extra copies may be more difficult to identify.

Hopefully, those are caught no later than the code review stage.

How to use the const keyword

In this course, you will learn how to use the const keyword in different contexts, such as:

  • const functions
  • const local variables
  • const member variables
  • const return types
  • const parameters
  • const and smart pointers
  • Rvalue references

Although the keywords constexpr, consteval, and constinit are related to const, we will not discuss those in this course.