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?
Constants provide some level of guarantee that code can't change the underlying value. This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors. Constants also provide a strong hint to the compiler for optimization.
A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With