11

In what situation would you need to make a variable constant?

If you wanted a variable to always keep the same value, couldn't you just not change it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    A Coffee table discussion brought into light - Welcome @Asthon – Ted Lyngmo Jul 05 '19 at 22:56
  • 1
    Related question about `private`: https://stackoverflow.com/q/4505938 – L. F. Jul 06 '19 at 00:23
  • Possible duplicate of [Can const-correctness improve performance?](https://stackoverflow.com/q/3435026/608639), [Does declaring C++ variables const help or hurt performance?](https://stackoverflow.com/q/3867001/608639), [What kind of optimization does const offer in C/C++?](https://stackoverflow.com/q/27466642/608639), [Are there any downsides to marking all variables you don't modify const?](https://stackoverflow.com/q/38925121/608639), etc. – jww Jul 06 '19 at 11:41

5 Answers5

12

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.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
8

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
3

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"

MattE
  • 1,044
  • 1
  • 14
  • 34
1

Although I cannot come up with a case where this is likely / good practice at the moment, consider that member functions (and free functions, of course) can be overloaded on const:

struct Foo {
  void Bar() {
    // One thing
  }
  void Bar() const {
    // Another thing
  }
};

// Later somewhere;
// which function gets called depends on
// whether the_foo is const or not
the_foo.Bar();

So making a variable const can change which function is called during overload resolution.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
1

Agreed with the accepted answer, but a less common consideration is this:

Static const data can be put in a read-only memory segment. On some systems, this can literally mean it can reside in ROM.

You may think, well why do this? Well consider something like the Ardruino Nano for example, it has a whopping 2KB of RAM.

Mapping the program's read-only data can only be done where the program's memory map includes the ROM segment, and on a lot of computers that would only apply to the bootloader, because all other code is loaded in from files (even if those files reside in ROM like on a mobile phone). However, I have seen it done like this, but I have also seen systems where the Read-Only segment(s) (and code segments) are copied to RAM on startup to improve speed.

Rodney
  • 2,642
  • 1
  • 14
  • 15