code:
const char * const key;
There are 2 const in above pointer, I saw things like this the first time.
I know the first const makes the value pointed by the pointer immutable, but did the second const make the pointer itself immutable?
Anyone can help to explain this?
@Update:
And I wrote a program that proved the answer is correct.
#include <stdio.h>
void testNoConstPoiner() {
int i = 10;
int *pi = &i;
(*pi)++;
printf("%d
", i);
}
void testPreConstPoinerChangePointedValue() {
int i = 10;
const int *pi = &i;
// this line will compile error
// (*pi)++;
printf("%d
", *pi);
}
void testPreConstPoinerChangePointer() {
int i = 10;
int j = 20;
const int *pi = &i;
pi = &j;
printf("%d
", *pi);
}
void testAfterConstPoinerChangePointedValue() {
int i = 10;
int * const pi = &i;
(*pi)++;
printf("%d
", *pi);
}
void testAfterConstPoinerChangePointer() {
int i = 10;
int j = 20;
int * const pi = &i;
// this line will compile error
// pi = &j
printf("%d
", *pi);
}
void testDoublePoiner() {
int i = 10;
int j = 20;
const int * const pi = &i;
// both of following 2 lines will compile error
// (*pi)++;
// pi = &j
printf("%d
", *pi);
}
int main(int argc, char * argv[]) {
testNoConstPoiner();
testPreConstPoinerChangePointedValue();
testPreConstPoinerChangePointer();
testAfterConstPoinerChangePointedValue();
testAfterConstPoinerChangePointer();
testDoublePoiner();
}
Uncomment lines in 3 of the functions, will get compile error with tips.
See Question&Answers more detail:os