Wednesday, December 19, 2007

const again

"use const whenever you need"

  • if the parameters are used for output, don't use const. Otherwise the parameters cannot output.
  • if the parameters are pointers, void StringCopy(char *strDestination, const char *strSource); const could avoid the change of *strSource.
  • if the parameters are 'pass by values', const is no use coz the function generate a temp variable automatically. If the function return a value - const int foo(void). 'const' is useless.
  • int foo(void) const; -- constant member function cannot change the member variables.
The followings are from book 'thinking in C++':
const int i = 100; // Typical constant
const int j = i + 10; // Value from const expr
long address = (long)&j; // Forces storage
char buf[j + 10]; // Still a const expression
int main() {
cout << "type a character & CR:";
const char c = cin.get(); // Can't change
const char c2 = c + 'a';
}

i is a compile-time const, but j is calculated from i. However, because i is a const, the calculated value for j still comes from a constant expression and is itself a compile-time constant. j can also be used in the determination of the size of buf because the compiler knows j is const and that the value is valid even if storage was allocated to hold that value at some point in the program.
In main( ), the value cannot be known at compile time. This means storage is required, and the compiler doesn’t attempt to keep anything in its symbol table. The initialization must still happen at the point of definition, and once the initialization occurs, the value cannot be changed. -- Jan. 30, 08

No comments:

Post a Comment