What is the importance of making a variable a constant?

Guarantees

If you were a perfect programmer, then sure, just don't change the variable. But six months down the road, when you haven't looked at this file in a long time and need to make a minor change, you might not remember that your variable shouldn't change. And if other code is written with that assumption, it's a recipe for disaster.

This goes tenfold if you're working with people on a project. A comment saying /* plz don't change this variable kthx */ is one thing, but having the compiler enforce that constraint is much harder to miss.

Optimizations

Constants can't be modified. This allows the compiler to do lots of clever things with them. If I write

const int foo = 5;

int some_function() {
    return foo;
}

The compiler can just have some_function return 5, because foo will never change. If foo wasn't const, some_function would always have to go read the current value of the variable. Also, if I have

const char foo[] = "Ashton Bennett is a cool C++ programmer";
...
// Somewhere else in the file
const char bar[] = "Ashton Bennett is a cool C++ programmer";

There's no reason to have both of those strings exist. If the compiler can prove that you never take a reference to either of them, it can fold the constants into one, saving space.


Yes but you are not taking into account that rarely will you be working on a project by yourself and the code you write may be around after you are gone so a person won't be able to ask you a question regarding a variable and its usage. By marking it constant you arre telling everyone "this value should never be changed in code"


The most important reason is to avoid bugs. By marking something const, you allow the compiler to catch any attempts to change it. For example, imagine if some variable is passed by reference to a function that changes it. If you marked that variable const, the compiler will catch that. If you don't, you'll have a bug that you'll have to find and fix -- hopefully before it causes some serious problems.

Marking variables, class member functions, parameters, and references const allows a large number of bugs that could easily get added inadvertently in complex code to be detected at compile time, before they have any chance to cause a program to execute incorrectly. Producing code without bugs is hard and any tool that can significantly help us do this is welcome.