What is the difference between const and volatile pointers?
What is the difference between const and volatile pointers?
Solution
The difference really comes down to the difference between const and volatile The only thing the two concepts have in common is grammar Const is executed by the compiler and says "programmers can't change this." Volatile means "this data may be changed by others", so the compiler will not make any assumptions about these data No change, The compiler may say, "I put this data from memory into a register, and because I didn't do anything to this data, I believe it is the same, and I don't need to read it again." when the data is marked volatile, the compiler will not make such an assumption (because others may have changed the data), so it will re read the data into the register
Now, do you ask for the difference
int *const p;
and
int *volatile q;
Or the difference between
const int* p;
and
volatile int* q;
In the former case, P is the pointer to int, and the pointer point cannot be changed by the programmer, while q is the pointer to int, and the pointer point can be changed by someone other than the programmer, so the compiler has no assumption about this pointer
So:
int *const p = (int*)malloc(sizeof(int)); int *volatile q = (int*)malloc(sizeof(int)); *p = 17; // legal; p = (int*)malloc(sizoef(int)); // not legal *q = 17; // legal; q = (int*)malloc(sizeof(int)); // legal
In the latter case, P is the pointer to int, which p cannot be changed by the programmer, and the pointer pointed by Q can be changed by someone other than the programmer, so the compiler will not make any assumptions about the data
int i = 17; int j = 34; const int *p = &i; volatile int *q = &i; *p = 51; // not legal p = &j; // legal *q = 51; // legal q = &j; // legal