c++ - int **const p does not behave like constant -


we know in int *const p, p constant pointer means address p holds cannot changed here in function foo change address.

how can possible?

int main(){     int = 10;     int *p = &i;     foo(&p);     printf("%d ", *p);     printf("%d ", *p); } void foo(int **const p){     int j = 11;     *p = &j;     printf("%d ", **p); } 

int **const p means p constant.

so following not allowed

p++; // bad p += 10; // bad p = newp; // bad 

but following fine:

if(p) *p = some_p; if(p && *p) **p = some_int; 

if want *p should not re-assigned, use following

int * const *p; 

if want neither p nor *p should changeable, use:

int * const * const p; 

and following make p, *p , **p read-only

  const int *const *const p; //  1          2      3 

1: **p constant
2: *p constant
3: p constant

use 1 or 2 or 3 or combination per requirement.

cdecl page: how read complex declarations int ** const p , const int *const *const p

related: c - 2 const mean?


Comments