0

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?

const int a = 1;
int b = 1;

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

Thanks

Community
  • 1
  • 1
  • Possible duplicate of [Does declaring C++ variables const help or hurt performance?](http://stackoverflow.com/questions/3867001/does-declaring-c-variables-const-help-or-hurt-performance) – James McNellis Feb 17 '11 at 20:52

2 Answers2

3

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    It also can affect optimization, but only when applied to an object definition, not when used with pointers. – Ben Voigt Feb 17 '11 at 20:58
0

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.