Constants and pointers
Variables that can be modified after a declaration are declared as constants if they cannot be modified in order to protect the variable, using the const modifier.
In C + +, a pointer variable is assigned a 4-byte (32-bit) block of memory to store the address pointing to the data, so the pointer type involves two concepts, the pointer itself (a 4-byte memory block), and a pointer to the data (4 bytes of memory block-stored address).
What if a pointer and a constant are combined?
Does declaring a pointer constant protect the pointer itself, or does the protection point to the data cannot be changed, or will both be protected?
Pointer constants
Definition: The pointer itself is a constant
Declaration: int * Const P = &a;//(const-modified P)
Attribute: Pointer pointing cannot be changed, but pointing to object is mutable (protection pointer itself does not protect pointing to data)
#include <iostream>using namespace Std;int main () {int a = 1, b = 2;int * Const p = &a;*p = 3;//can be compiled, can be changed to point to data P = &b;//cannot compile, cannot re-point to new object (the pointer itself cannot be changed) return 0;}
constant Pointer
Definition: Pointer to constant
Declaration: const int *P = &a; or int const *P = &a; (Const-Modified is *P)
Attribute: Pointer to variable, but pointer to object immutable (protection pointing to data does not protect the pointer itself)
#include <iostream>using namespace Std;int main () {int a = 1, b = 2;const int *p = &a;*p = 3;//cannot be compiled, cannot be changed to point to data P = & amp;b;//can be compiled and can be re-pointed to the new object (the pointer itself can be changed) B = 3;//But the original variable can still change the data that P points to return 0;}
Pointer variable pointing to constant
Definition: The pointer itself is a constant, pointing to the object does not change
Declaration: Const INT * Const P = &a; (The const modifier is *p and p)
Features: Protection of pointing data also protects the pointer itself
#include <iostream>using namespace Std;int main () {int a = 1, b = 2;const int * Const P = &a;//both protect *p = 3;//cannot be compiled , cannot change point to data P = &b;//cannot compile, cannot re-point to new object (the pointer itself cannot be changed) return 0;}
Assigning values between constants
#include <iostream>using namespace Std;int main () {int const A = 1;int Const *P1 = &a;//Correct, A is constant immutable, assigned to pointer P1 after a is also immutable I NT * Const P2 = &a;//is not correct, a is constant, assigned to pointer P2 after a cannot guarantee immutable int const * Const P3 = &a;//Correct, A is constant immutable, assigned to pointer P3 after a also immutable return 0;}
Java Programmer learns C + + 's constant pointers and pointer constants