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.
Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.
Constants can make your program more readable. For example, you can declare: Const PI = 3.141592654. Then, within the body of your program, you can make calculations that have something to do with a circle. Constants can make your program more readable.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
What is the benefit of const keyword in programming? Specifying a variable as const states that the variable's value should never change after the initial assignment. This allows the compiler to perform additional tests at compilation (validating your code).
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.
In terms of performance? No, probably not. It looks like your array could be static
too, and then perhaps yes.
In terms of code style? Possibly. Though the addition of const
makes your code a little verbose, it also makes clear that the data is not to be modified. This is both documenting and safe.
Ideally, all objects in C++ would be constants by default, and you'd have to write mutable
to make them variables. It's all backwards!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With