c - How does the const keyword affect a pointer that is pointing towards a const variable? -
if consider this:
int *var1; const int *var2 = var1; why
*var1 = x; compile ,
*var2 = x; does not?
in case
*var2 = x; fails compile error message (approx),
error: assignment of read-only location
*var2*var2 = 10; ^
because have marked value of const qualified.
to elaborate, can read statement like
const int *var2; as, declare var2 pointer const int. value pointed var2 constant , cannot changed.
in case want pointer const-qualified, need write like
int * const var2; which declaring var2 const pointer int.
so, later attempt assign var2 produce error, accessing *var2 work fine, value pointed pointer not const-qualified anymore.
Comments
Post a Comment