Const modifies a pointer in three cases:
1. Const decorates Pointers — constant Pointers
const int * p = &a;
The point of a pointer can be changed, but the value it points to cannot be changed.
Memory tip: Const followed by *p indicates that the value to which the pointer points cannot be modified.
2. Const decorates constants — pointer constants
int * const p = &a;
The point of a pointer cannot be changed, but the value it points to can be changed.
Memory tip: Const followed by p, indicating that the pointer cannot be changed, p for address.
3. Const modifies both Pointers and constants
const int * const p = &a;
Neither the pointer nor the pointer value can be modified.
int main(a)
{
int a = 10;
int b = 10;
// Contst modifies the pointer. The pointer pointer can be changed, but the pointer value cannot be changed
const int * p1 = &a;
p1 = &b; / / right
//*p1 = 100; An error
// Const modifies constants. The pointer to a pointer cannot be changed. The value to which a pointer points can be changed
int * const p2 = &a;
//p2 = &b; error
*p2 = 100; / / right
//const decorates both Pointers and constants
const int * const p3 = &a;
//p3 = &b; error
//*p3 = 100; error
return 0;
}
Copy the code