Alex Rivera | Logout

Is there any benefit to declaring local variables const?

Asked 2011-08-03T22:22:37.833
12

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.

Edit
Report

2 Answers

23

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.

answered 2011-08-03T22:26:58.083
2

Talking about performances, but also code readability, you should create the "colors" variable outside the function ( since a hundred-sized array is quite a huge amount of code, masking the logic of the function) either in an initialization function, or at global level. If you don't consider extract this variable, at least, make it static.

If this array is used only during a short period during the program execution, you may consider fill it before the first call to getcolors and eventually free it when you're sure you will not require it anymore.

answered 2011-08-03T22:39:57.530

Your Answer