Reference URL:
1. http://blog.csdn.net/miyunhong/archive/2010/09/24/5903857.aspx
2. http://developer.51cto.com/art/201001/180130.htm
3. http://developer.51cto.com/art/201002/182348.htm
4. http://tech.sina.com.cn/s/2004-09-17/0735426801.shtml
5. http://blog.chinaunix.net/u/30686/showart_524480.html
Example 1:
# Include <iostream>
Using namespace std;
Void main ()
{
Const int qq = 456;
// Int * const p indicates declaring a const pointer to a non-const object
Int * const p = (int * const) & qq;
* P = 123;
Cout <qq <endl; // output 456, not changed
Cout <* p <endl; // output 123
Int num = 100;
// The following error is returned: p = & num;
Int * const p2 = & num;
* P2 = 6;
Cout <num <endl; // output 6, value changed
Cout <* p2 <endl; // output 6
}
Example 2:
# Include "iostream"
Using namespace std;
Void main ()
{
Const int num = 123;
Int * p = const_cast <int *> (& num );
// It can also be written as follows: int * p = (int *) & num;
* P = 456;
Cout <num <endl; // output 123, value not changed
Cout <* p <endl; // output 456
}
Example 3:
# Include "iostream"
# Include "My. h"
Using namespace std;
Void main ()
{
Extern const int;
Int * p = (int *) &;
Cout <* p <endl; // output 46
* P = 99; // the error message "the memory cannot be written" is returned when the code is executed"
}
My. h is as follows:
Extern const int a = 46;
Example 4:
Void Fun (const int arr [])
{
Int * p = (int *) arr;
* P = 55;
}
Void main ()
{
Int arr [3] = {3, 6, 9 };
Fun (arr );
Printf ("% d \ n", arr [0]); // output 55
Int num = 1;
Int const * p = & num;
Int * p2 = (int *) p;
* P2 = 123;
Printf ("% d \ n", num); // output 123
}
Fifth example:
Const int num = 789;
Const int * p;
P = & num;
Int * p2 = (int *) p;
* P2 = 22;
Printf ("% d \ n", num); // output 789, presumably because the code becomes printf ("% d \ n", 789) after the program is compiled ), this also proves that it is wrong to change the constant into a read-only variable by performing the & get address operation on the const constant.
Printf ("% d \ n", * p); // output 22
Printf ("% d \ n", * p2); // output 22