开发者

Why marking variables as a constant? [duplicate]

开发者 https://www.devze.com 2023-02-11 12:50 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Does declaring C++ variables const help or hurt performance?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Does declaring C++ variables const help or hurt performance?

Besides the point of you can't change cost variables, does it use less memory or can it access the values faster?

cons开发者_JAVA百科t int a = 1;
int b = 1;

Taking into account it's the same global, local and class member.

Thanks


does it use less memory or can it access the values faster?

Usually neither. It just makes the program more robust because you (or other people) cannot change the value accidentally.

This makes especially sense in public APIs when you want to show consumers that you won’t modify their values. Every modification of a variable means a change in the program state. In order for programmers to be sure that their program works correctly they need to keep track of the state, and this is tremendously more difficult if they don’t know when or how their variables are changed.

The primary purpose of const is therefore documentation of semantics and this is a very powerful purpose. Use const often.


It's not faster to reference a const variable. Use the restrict parameter for that.

The standard library string functions will use const to let you know there are no side-effects to your data structures, it's used to establish a read-only policy and avoid side-effects.

0

精彩评论

暂无评论...
验证码 换一张
取 消