3

following code in the picture is a example to illustrate pointer to a constant integer. My question:

  1. Since int w is not declare as a constant integer, why it says that the pointer is pointing to a constant integer?

  2. 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...

enter image description here

2
  • "It changes the thing in the pointer, not the constant value itself..." is not correct. The previously line (p = &w) assigned a new value to the pointer while the last line (*p = 3) goes and mucks with the object pointed to. Commented Dec 7, 2015 at 2:54
  • What on earth is this mess you're pasting into your question? Commented Dec 7, 2015 at 3:02

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

According to what you say, 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...
a pointer to constant can be changed (i.e. it points to other variables) but not the value it points to

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.