Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the importance of making a variable a constant? [closed]

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?

like image 695
Ashton Bennett Avatar asked Jul 05 '19 22:07

Ashton Bennett


People also ask

What is the purpose of a constant?

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.

What happens when a variable is constant?

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.


1 Answers

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.

like image 172
Silvio Mayolo Avatar answered Sep 17 '22 00:09

Silvio Mayolo