Here is a question which makes me puzzling and would appreciate if anyone can give me some insight.
For the following function f1
void f1(const int *ptr) { ... }
I learned that if f1 does not need to make change to *ptr, then declaring ptr as const int * will be preferred to make the function more flexible. In particular, the f1 will work for both i1 and i2 in the following.
1 2 3 4 5 6
|
void main(int argc, char **argv) {
int i1 = 20;
const int i2 = 30;
f1(&i1);
f2(&i2);
}
|
Following this logic, I would think that the function f2
void f2(const int **pptr) { ... }
will be preferred instead of the following
void f2_another(int **pptr) { ... }
if I am not going to change **pptr.
However, declaring f2 as in the first case, I got an compilation error when I pass a pointer to pointer to non-const int.
Can someone explain why this is not allowed? What are the differences between f1 and f2? What is the solution for the compilation error? Is it preferred not to use const for pointer-to-pointer in this case (as oppose to the case of const pointer)?
Thanks a lot.