-3

This is what I have:

const int x = 10;
int *ptr = &x; //error: 'initializing': cannot convert from 'const int *' to 'int *'

I know x can't be modified after initializing and I know how to fix this compilation problem, but why can't I use a pointer (in this case ptr) to point to x?

Although it is a const int, I don't understand the reason behind of why can't I point to it, as I can still use *ptr to represent x, right?

PzrrL
  • 53
  • 9

1 Answers1

4

Because ptr is of type int*, i.e. it points to a non-const int. This allows you to modify ptr using *ptr. To prevent the const variable from being modified, the compiler prevents the initial assignment to a non-const pointer.

Making ptr point to a const int will naturally fix the problem: const int* ptr = &x;

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • Because I am pointing to a const int, so even if I point to x, it is useless because I cannot modify the value using *? – PzrrL May 15 '16 at 17:55
  • @PzrrL yes, because `x` is a `const int` – Rakete1111 May 15 '16 at 17:56
  • @Rekete1111 Although it is a `const int`, I don't understand the reason behind of why can't I point to it, as I can still use `*ptr` to represent `x`, right? – PzrrL May 15 '16 at 18:08
  • @PzrrL you can point to it (`const int* ptr = &x;`), you just have to define `ptr` as a pointer to a **`const int`**, not just an `int` – Rakete1111 May 15 '16 at 18:09
  • @PzrrL: If someone has an `int* ptr`, and does `*ptr = 99` (after verifying that `ptr` is not null), then it is perfectly reasonable for them to expect `*ptr == 99`. But if `ptr` is storing the address of a const value, then that won't work. So the language doesn't even allow you to do that (at least, not without a cast). – Benjamin Lindley May 15 '16 at 18:16
  • @BenjaminLindley Can I understand that in this way? Because after `ptr` pointing to a `const int`, when I use `*ptr` to do assignment, it is illegal. To avoid this, the language don't even allow me to do use `int *ptr` to point to a `const int`? – PzrrL May 15 '16 at 18:23
  • @PzrrL: That is correct. – Benjamin Lindley May 15 '16 at 18:27