Does const have practical applications like reducing memory usage?

Okay so we know that we use the modifier 'const' when a certain variable isn't going to vary along the execution of the program.

So from what I know 'const' is going to alarm the compiler if the compiler detects that the certain variable to being assigned twice.

So const can be a good practice.

But does it have a real application behind the scenes?

You know how int compared to long int takes less bytes because of the fact that int is much smaller, similarly is there anything like that happening with const?

What I mean is, does const do anything other than warn the compiler?


Because explicitly declaring a variable as const and not assigning it twice is the same as declaring just a variable and not assigning it twice.

^^ So is that the case?
Const is a sort of protection. If something isn't supposed to change, like the speed of light, some unexpected input/scenario may happen that could potentially alter it. Even though you may not put any mechanism/code that would allow for the variable to change, better safe than sorry.

As for performance changes, the answer is no. I've heard some say that it makes loading up variables faster since the compiler knows that the variable wont change, but I can't attest to that information's accuracy. Moreover, even if there was a performance gain as mentioned, it would be so insignificant I doubt it warrant the time to write out "const" in of itself.
Thanks zapshe that makes sense.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{
   int M = 10;
   int a[M];            // <==== Illegal (at the moment) in standard C++

   const int N = 10;
   int b[N];            // <==== OK; N is a compile-time constant
}


Many C++ compilers would allow this (partly because it is legal in the latest version of C, and also in other languages).

I suspect setting aside the amount of memory you need at compile time would be faster than allowing the program to acquire it at run time, though I'm not sure which bit of memory (stack or heap) would be taken.
Last edited on
const helps you to write better code. It actually prevents you from abusing variables (modifyiing the improperly).

It also helps the compiler to generate faster and smaller code. For instance: The compiler does not consider a const variable unless it is used. Hence you can place const variables all over your program and it has no effect to the size of the executable unless you use them.

https://stackoverflow.com/questions/212237/constants-and-compiler-optimization-in-c
Last edited on
Topic archived. No new replies allowed.