Reputation: 145
following code in the picture is a example to illustrate pointer to a constant integer. My question:
Since int w is not declare as a constant integer, why it says that the pointer is pointing to a constant integer?
why we cannot try the last line?
If the pointer to a constant should not be assigned to any other value after assigning to the first value, so what makes the difference between a pointer to a constant and a constant pointer then? ( For my understanding, a constant pointer cannot be changed, but a pointer to constant can be changed...
Upvotes: 3
Views: 612
Reputation: 179422
Think of const
as a restriction - it prevents you from writing. Then the meaning is clear: const int *
adds a restriction that may not exist on the base variable.
C lets you add this kind of restriction freely. The thing you can't do is to remove restrictions - you can't make a int *
point at a const int
without casting.
Upvotes: 3
Reputation: 58868
C allows a "pointer to const int
" to actually point to a non-const int
, as you found out. It doesn't cause any problems, so why not allow it?
The pointer doesn't remember whether it's pointing to a const int
or to a normal int
, so you always have to treat it as if it's pointing to a const int
. That means *p = 3;
isn't allowed, because the compiler doesn't know for sure* that *p
isn't a const int
.
* Modern compilers might well be able to figure this out, but the language says they have to pretend they can't, and they won't always be able to anyway.
Upvotes: 4