1. Const type variables must be initialized during Declaration; otherwise, an error will be reported.
2. Define a non-const object in the global scope, which can be accessed throughout the program
For example:
// File1.cc
Int counter;
// File2.cc
Extern int counter;
++ Counter;
Defining the const variable in the global scope means that this variable is a local variable of the file. You must specify the variable type as extern to use this variable throughout the program.
For example:
// File1.cc
Extern const int counter = 0;
// File2.cc
Extern const int counter;
++ Counter;
3. Const application and non-const reference
A non-const reference can only be bound to a variable of the same type as the reference, and cannot be initialized to the right value.
For example:
Double A = 1.22;
Int & B = A; // Error
Double & C = A; // correct
Int r = 10;
Int & D = R + 55; // Error
Because the compiler will convert the Code:
Int temp =;
Int & B = temp;
That is to say, B is not bound to A, but to temp. It is impossible to change a through B, so this is illegal.
The const reference can be bound to different types or the right value.
For example:
Double A = 1.22;
Const Int & B = A; // correct
Const double & C = A; // correct
Int r = 10;
Const Int & D = R + 55; // correct
4. pointer to const
For example:
Double A = 1.01;
Const double * B = &;
* B = 2.1; // This is obviously incorrect.
A = 2.1; // This is correct. The values of A and * B are both 2.01. Some people call it a pointer to const.
5. Const pointer
For example:
Int A = 10;
Int * const B = & A; // This means that B can only point to
A = 20;
* B = 30; // The value of the variable can be changed in the preceding two statements.
It is also related to Article 4 and interesting:
Typedef int * pint;
Int value = 10;
Const pint a = & value;
Pint const B = & value;
Int * const c = & value; // The effect of the three statements is consistent.