Search code examples
c++variablesconstants

Is there any benefit to declaring local variables const?


If I have a function which only exists for a short amount of time, does making the list of colors a constant make a difference?

string getrandcolor(){
    const string colors[5] = {"red", "blue", "green", "yellow", "purple"};
    return colors[rand() % 5];
}

Note: The actual list of colors contains hundreds of colors not just the small sample I have shown, not sure if this makes a difference either.


Solution

  • It prevents you from accidentally overwriting variables that you didn't mean to change. "Oops!"-protection is probably const's most important function.

    Hypothetically a compiler could divine some kind of optimization from knowing a variable isn't supposed to change, but my testing has never found one that actually does something meaningful in the situation you describe.

    const static does have an important difference in your particular code sample. Because your colors[] array is local, it must be constructed afresh each time the getrandcolor() function is called. That means the string constructor gets run five times each time you call getrandcolor(), which is very wasteful. const static means that the data is constructed only once — the first time the function is run — and put into a shared memory space.