Pradeep Kumar Pradeep Kumar - 1 month ago 10
C Question

Why the location pointed by a pointer to const is assignable by other variable?

I have written this piece of code

#include <stdio.h>
int main() {
int b = 15;
const int *foo = &b;
//b = 20;
*foo = 20;
printf("%d", *foo);
return 0;
}


This means that the location that
foo
is pointing to cannot change. That means
b
cannot change . But when I uncomment the line
b = 20
. It doesn't show any error and I get the output
20
. While in this piece of code I get this error

main.c: In function 'main':
main.c:15:10: error: assignment of read-only location '*foo'
*foo = 20;


If
*foo
that is
b
is read only location, why can I change its value
b = 20
?

Answer Source

What does

 int b=15;
 const int* foo=&b;   

mean?

It means,

  • b is a modifiable int object.
  • &b has type int *. The declaration for foo converts &b to type const int *. This is a valid qualification conversion.
  • int object pointed by foo must not be modified using foo.

The above qualification conversion does not invalidates the declaration of b, i.e. it still is modifiable. b can still be used to update its value but *foo can't be used.

Think const as a promise. You promised the compiler that you will not change the value at the location pointed by foo, but no one is stopping you to break that promise by changing that value at that location by other means.