Search code examples
c++constants

What is the point of the "const" keyword in C++?


What is the point of using the keyword const?

For example, when making a game, one of the first things to do is to set the width and height of it. And most of the time you'll use for example:

const int Width

and

const int height

Now I know that you should do it like that, because the width and height of the screen will not change throughout the game, but what is the point of doing so? you can do the same thing without using const and it will work just fine.

That was just an example. so what I'm confused about right now is:

What is the point of using the const keyword anywhere if you won't change the variable anyway?


Solution

  • Non-exhaustive list of reasons:

    1. Software Engineering (SWE). SWE is not just programming, but programming with other people and over time.

      const allows to explicitly express an invariant, which lets you and others reason about the code. As the program becomes bigger, these invariants cannot be just memorized. That's why encoding them in the programming language helps.

    2. Optimization opportunities.

      With the knowledge that certain values will not change, the compiler can make optimizations that would not be possible otherwise. To take this to the max, constexpr means that a value will be known at compile time, not just at run-time. This becomes even more important in potentially multi-threading contexts.

      Example: What kind of optimization does const offer in C/C++?

      I leave out whole program analysis which would require a much longer answer and almost certainly is not applicable to generic C++ programs. But whole-program-analysis will allow reasoning of the analyzer or compiler about constness of variables as they get passed between functions, translation units and libraries.