简体   繁体   中英

Is there any benefit to declaring a const rather than a variable inside a function?

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.

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!

如果您在谈论性能,那么: ,它不会有任何区别。

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

  • Correctness: the compiler will ensure that you won't accidentally change the value of the variable.
  • Clarity: you clearly document that the variable is a constant.

(By the way, I am not sure what is constant in that specific example. More soon...)

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.

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 all it knows, bar() takes the value of global_ptr , converts it to int* , and modifies x through it. This would be somewhat risky coding, but casting away a const qualifier and mutating is valid provided that the referand is really mutable, so the compiler must allow for it.

But, if x were marked const then it would be invalid for bar() to cast away const and mutate, and so the optimizer is free to assume that x still holds the value 1 when it is printed.

Optimizers certainly do identify compile-time constants for this kind of optimization, so I wouldn't be surprised to see it make a difference to emitted code. How much difference it makes to performance, I don't know. It's not hard to generate cases where identifying a constant can for example replace an (expensive) division with some (cheaper) bit twiddling, or can allow expressions involving x and a bunch of other constants to be calculated at compile time instead of runtime.

Also, link-time optimization might allow bar to be inlined, in which case the link-time optimizer can inspect its contents more closely, and might be able to rule out its modifying x even in the non-const case.

In your example, though, no reference to colors can escape to unknown code, so the difference doesn't arise. Anyway, a const string is probably harder to optimize with than a const int, so there's even less chance you're enabling some brilliant optimization by using const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM