-8

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?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Dissoantn Void
  • 145
  • 1
  • 3
  • 9
  • 4
    *You* won't change the variable, but what about the junior developer that got hired last week? He might not know that the variable isn't supposed to be changed. By marking the variable *const*, you allow the compiler to gently inform him that he has made a mistake by trying to change its value, rather than allowing a bug to slip into the codebase where it will cost your QA team several man-hours of work to find and fix. – Jeremy Friesner Apr 02 '20 at 20:14
  • 1
    Detecting bugs at compile time > detecting bugs at runtime. – Algirdas Preidžius Apr 02 '20 at 20:16
  • 1
    ... and btw, "the junior programmer" will often be you, six weeks later and running on not enough coffee ;) – Jeremy Friesner Apr 02 '20 at 20:17
  • 2
    *"if you won't change the variable anyway"* - You might not intend to change the variable. But over time you may forget, or you may get confused in other parts of the code, or you may make a mistake, etc. If you are *absolutely certain* that your code will always be infallible and you are incapable of mistakes, then you don't need a compiler anyway. Just write perfect machine code. If, on the other hand, you'd like to make use of tools to help with the development process, `const` is a handy one to explicitly define that the value shouldn't change. – David Apr 02 '20 at 20:18
  • A great talk by Kate Gregory on the use or omission of certain keywords, including `const`. Worth the hour. https://www.youtube.com/watch?v=kYVxGyido9g – JohnFilleau Apr 02 '20 at 20:26

5 Answers5

5

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.

Unapiedra
  • 15,037
  • 12
  • 64
  • 93
2

Without const, you have to remember to not change the variable. The larger your program becomes, the harder it gets.

It also has some other useful effects:

const int a = 10;
int b[a]; // Doesn't work if `a` is not `const`.

// ...

void foo(const int &a) {};
void bar()
{
    foo(42); // Doesn't work if the parameter is a non-const reference.
}
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

To stay with your example, suppose I write a game library that has a

struct game {
    int width;
    int height;
    int area;
    game(int w, int h) : width(w),height(h),area(w*h) {} 
};

Now you use my library and because I did not write any documentation (evil me) you just start writing code and try what you can do with that class. You write code

#include <iostream>
int main() {
    game g{3,5};
    g.width = 12;
    std::cout << g.width << " * " << g.height << " == " << g.area;
}

and get output:

12 * 5 == 15

You will complain that the code I wrote is broken because you get non-sense results when you use it. If however I had used const for things you are not supposed to modify:

struct game {
    const int width;
    const int height;
    const int area;
    game(int w, int h) : width(w),height(h),area(w*h) {} 
};

Then you would get a nice error message that tells you that you tried to modify something that you are not supposed to modify:

prog.cc: In function 'int main()':
prog.cc:11:15: error: assignment of read-only member 'game::width'
     g.width = 12;

Once you fixed your code to

#include <iostream>
int main() {
    game g{3,5};
    std::cout << g.width << " * " << g.height << " == " << g.area;
}

All const could be removed and the output would not change. However this is not always the case. For example member functions can have const and non-const overloads that can do different things depending on whether the method is called on a const or on a non-const object:

#include <iostream>
struct foo {
    void sayHello() const {
        std::cout << "I am a const object\n";
    }
    void sayHello() {
        std::cout << "I am a non-const object\n";
    }
};

int main() {
    const foo f;
    f.sayHello();
    foo g;
    g.sayHello();
}

output:

I am a const object
I am a non-const object

Conclusion:

const is mainly to ensure correctnes and to avoid mistakes. const can also be used to make const objects behave differently than non const objects. There is more to it and details you can read up eg here.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

Having something declared const, compared to a value set with #define for instance, allows you to declare something that the compiler will never let you alter, but that will still keep all of the other properties of a regular variable.

In particular, it will keep a certain place in memory and a pointer on it can be obtained with « & », keeping all read-only routines that use to work on regular object compatible with it.

It's especially useful when your constant object is not a simple native type variable, but rather a complicated object spawned from a class and that still need to be initialized through a constructor.

Also remember that const is a type qualifier, than can apply not only on variable declarations, but also on arguments of a function prototype. In this particular case, this will enable your function to accept both constant or variable arguments.

Such a constant argument could be, for example, a double-quoted "string", which is const char *-typed, because the string is directly part of the code itself and defined at compilation type. Without a const qualifier, nothing could prevent your function from trying to write in it, nor warn the programmer that it's forbidden.

Obsidian
  • 3,719
  • 8
  • 17
  • 30
-1

const is for a constant variable, that it means nobody should change it, or maybe for const T & passing non-trivial type as parameter, or maybe for making a pointer constant, or for value pointed from the pointer (const *P *variable)

F.Guerinoni
  • 277
  • 2
  • 12