Is there any use for declaring a constant rather than a variable inside a function?

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

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

Note. The actual color list contains hundreds of colors, and not just a small sample that I showed, not sure if this also matters.

+7
source share
6 answers

This prevents accidentally overwriting variables that you did not want to change. "Oops!" - protection is probably the most important const function.

Hypothetically, the compiler can explain some kind of optimization, knowing that the variable should not change, but my testing never found that it really does something significant in the situation you are describing.

const static has an important difference in your specific code example. Since your colors [] array is local, it must be recreated every time the getrandcolor() function is getrandcolor() . This means that the string constructor runs five times each time you call getrandcolor() , which is very wasteful. const static means that the data is built only once - at the first start of the function - and is placed in a shared memory space.

+16
source

In terms of performance? No, probably not. It looks like your array could be static too, and then maybe yes.

In terms of code style? Maybe. Although adding const makes your code a little verbose, it also makes it clear that data is not subject to change. This is documentation and security.


Ideally, all objects in C ++ would be constants by default, and you would need to write mutable to make them variables. All this back!

+5
source

If you are talking about performance, then: no , that shouldn't matter.

+2
source

By declaring a local variable const, you get the following benefits:

  • Correctness: the compiler ensures that you do not accidentally change the value of a variable.
  • Clarity: you clearly confirm that the variable is constant.

(By the way, I'm not sure what is constant in this particular example. Rather ...)

+2
source

Speaking about the performance and readability of the code, you should create the β€œcolors” variable outside the function (since an array of hundreds of sizes is a fairly large amount of code masking the logic of the function) either in the initialization function or globally. If you do not consider retrieving this variable, at least make it static.

If this array is used only for a short period of time during program execution, you can consider filling it before the first call to getcolors and, ultimately, freeing it when you are sure that you will no longer require it.

+2
source

A slightly different example:

 const int *global_ptr = 0; void bar(); void foo() { int x = 1; global_ptr = &x; bar(); std::cout << x << "\n"; } 

The compiler cannot optimize the last line to use the value 1 , because for everything it knows, bar() takes the value global_ptr , converts it to int* and modifies x through it. It will be a bit of a risky coding, but dropping the const specifier and mutation is valid provided that the link is really changed, so the compiler must allow this.

But if x were marked as const , then it would be wrong for bar() to discard const and mutate, and so the optimizer may assume that x still stores the value 1 when it is printed.

Optimizers, of course, identify compile-time constants for this kind of optimization, so I won’t be surprised if this changes the source code. What is the difference in performance, I do not know. It is not difficult to generate cases where the identification of a constant can, for example, replace the (expensive) division with some (cheaper) bit or allow expressions involving x and many other constants that will be computed at compile time instead of runtime.

In addition, connection time optimization may include bar , in which case the link time optimizer can more carefully check its contents and may be able to exclude its modification x even in non-const.

In your example, however, a link to colors may escape to an unknown code, so the difference does not occur. Anyway, a constant string is probably harder to optimize than const int, so there is even less chance that you will allow brilliant optimization with const .

+1
source

All Articles