Search code examples
programming-languagesconstants

The Benefits of Constants


I understand one of the big deals about constants is that you don't have to go through and update code where that constant is used all over the place. Thats great, but let's say you don't explicitly declare it as a constant. What benefit(s) exist(s) to take a variable that HAPPENS to actually not be changed and make it a constant, will this save on processing, and/or size of code...etc?

Basically I have a program that the compiler is saying that a particular variable is not changed and thus can be declared a constant, I just wanted to know what the benefit to adding the constant qualifier to it would be, if it makes no difference then making that change adds no value and thus no point wasting time (this same scenario occurs in more then one place) going back and "fixing" all these variables.


Solution

  • If you declare a variable to be a constant, then the optimizer can often eliminate it via 'constant folding' and thus both speed up your program and save you space. As an example, consider this:

    var int a = 5;
    const int b = 7;
    ...
    c = process(a*b);
    

    The compiler will end up creating an instruction to multiply a by 7, and pass that to 'process', storing the results in c. However in this case:

    const int a = 5;
    const int b = 7;
    ...
    c = process(a*b);
    

    The compiler will simply pass 35 to process, and not even code the multiply. In addition, if the compiler knows that process has no side effects (ie, is a simple calculation) then it won't even call process. It will just set c to be the return value of process(35), saving you a function call.