0
int main() {
    const int i = 1;
    const int* p = &i;
    int j = 2;
    const int* q = &j;
    j = 3;
    printf("%d", *p + *q);
    return 0;
}

I have this code, and I try to understand how it compiles. p and q are pointers to constant integers but j isn't declared as constant. Moreover, j changes into 3.

How does it work?

Thanks!

Ben Azran
  • 3
  • 1
  • 3

1 Answers1

1

On the 5th line, you're assigning the address of variable j to q. This do not enforce any constraint over j, just on pointer q. Through q the compiler won't allow you to change pointed value, however j remains writeable and the line j = 3; is legal.

See What is the difference between const int*, const int * const, and int const *?

Neywat
  • 103
  • 7