I read many old questions, many answers about const
keyword in a declaration to deeply understand the syntax of declarations.
I played with const
and I am now a little bit confused with this example :
int i;
i=1;
int const *ptr_i;
ptr_i=&i;
printf("%d\n",*ptr_i);
i=2;
printf("%d\n",*ptr_i);
If int const *
is a pointer to a constant integer, why ptr_i=&i;
is allowed ? i
is not a constant integer.
Moreover, if the value of i
is changed from 1 to 2 (obviously, it is possible because i
is not a constant integer), the second printf
displays 2. I am not surprised because the value of i
has been changed and ptr_i
is a pointer to i
.
I, also checked that he value of ptr_i has not changed ( printf("%p ",ptr_i)
).
Where is my misunderstanding ?
If
int const *
is a pointer to a constant integer,…
int const *
is not a pointer to a constant integer. It is a pointer to an int
for which the int
type is qualified with const
.
const
is a misnomer. “Read only” is closer to an accurate description; it means that “with this type, the value will only be read.” Meaning that somebody else with a different pointer (same value, different type) can write to the object.
It is not purely read-only either. In C, if an object was defined without const
, but you have a pointer to it of type const int *
, you can convert the pointer to int *
and use the new pointer to modify the object, and that is defined by the C standard. const
was added to the language late, so it is somewhat grafted on rather than fully integrated, and it does not serve as a complete solution for preventing writes to objects. Mostly, it performs an advisory service: When a type is qualified with const
, the compiler must warn you about attempts to use it directly to modify an object it points to. That helps programmers avoid bugs.