Monika Singla
Monika Singla

Reputation: 21

pointer to a constant pointing to normal variable

char var = 'a';
const char *ptr;
ptr = &var;
*ptr = 'b'; //(i understand this is wrong)
var = 'b'; // (why is this wrong)

I cant change the value of "var". does that mean i have changed the declaration of "var" from char to const char by assigning it to to this pointer(pointer to a constant). So doesn't the rule should be that pointer to a constant should only have address of constant variables. Thanks in advance.

Upvotes: 0

Views: 992

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477590

I cant change the value of "var".

Yes you can. You're doing it in the final statement, var = 'b';

does that mean i have changed the declaration of "var" from char to const char

No. var is, has always been and will always be a mutable char.

So doesn't the rule should be that pointer to a constant should only have address of constant variables.

No. The only thing special about a pointer-to-const is that you cannot change the pointed-to object through this particular pointer. It's entirely possible to change the object in some other way, as you are demonstrating yourself, as long as the object itself is mutable.


Here's another way of understanding what's going on:

  1. There exists an object which is a mutable char.
  2. When you evaluate the id-expression var, you obtain a modifyable lvalue of type char which designates that object. Colloquially, you can say that "the object has the name "var".
  3. When you evaluate the expression *ptr, you obtain an (unmodifyable) lvalue of type const char which also designates the same object we mentioned in (1).

There are in general many ways to designate the same object, which is to say, there are many ways to refer to the object as a value of some kind of expression. Sometimes these values are mutable, and sometimes they are immutable. (It is only if the object itself is const that it is not allowed to modify it through a mutable value; but it is usually quite hard to obtain a mutable value that designates a constant object — you'd need something like a const_cast, or a qualifier-discarding cast in C.)

Upvotes: 5

JS1
JS1

Reputation: 4767

There's nothing wrong with this line:

var = 'b'; // (why is this wrong)

Did your compiler complain about it? Mine did not.

Upvotes: 1

Related Questions