Object-oriented is an important feature of C + +.
But C + + on the basis of a new increase in the number of optimization is also very dazzling on the const directly can replace C in the #define the following points are very important, learning bad consequences are also very serious
Const
1. Qualifier declaration variable can only be read
const int i=5;
int j=0;
......
I=J//illegal, resulting in compilation errors
j=i;//Legal
2. Must initialize
const int i=5;//Legal
const int J;//Illegal, causing compilation errors
3. Referring to the const constant in another connection file
extern const int i;/Legal
extern const int j=10;//illegal, constants cannot be assigned again
4. Easy to type check
Use the Const method to make the compiler more aware of what is being handled.
#define I=10
Const LONG &i=10;/*dapingguo reminder: Because of compiler optimizations, I do not allocate memory when Const long i=10, but have 10 directly into subsequent references so that there are no errors in future code, especially for the purposes of preaching. &i explicitly gives the memory allocation of I. However, once you turn off all optimizations, even a const long i=10 can cause subsequent compilation errors. */
char h=i;//Nothing wrong
Char h=i//compilation warning, which may result in incorrect assignment due to a truncated number.
5. Can avoid unnecessary memory allocation
#define STRING "Abcdefghijklmnn"
const char string[]= "ABCDEFGHIJKLMN";
......
printf (string);//Assigned first memory to STRING
printf (string);//Allocate memory once for string, no longer assigned
......
printf (string);//allocated second memory for STRING
printf (string);
......
Because the const definition constant is given a corresponding memory address from the assembly point of view, rather than giving an immediate number like #define, the const-defined constant has only one copy during the program's operation, while the #define-defined constant has several copies in memory.