1

My question is that as per my sample, I have been able to point to a non-constant variable by a pointer which is meant to point to a constant variable. My sample goes like this :-

int tobepointed = 10;
int tobepointed1 = 11;
int const *ptr = &tobepointed;
cout << "\nPointer points to the memory address: " << ptr;
cout << "\nPointer points to the value: " << *ptr;
tobepointed = 20;
cout << "\nPointer points to the memory address: " << ptr;
cout << "\nPointer points to the value: " << *ptr;
ptr = &tobepointed1;
cout << "\nPointer points to the memory address: " << ptr;
cout << "\nPointer points to the value: " << *ptr;

Now this block of code goes on correctly without any compile or runtime error. Also consider the pointer *ptr. If i declare the ptr like any normal pointer like :- int *ptr;

Then also the output is same, so why do we need the concept of 'pointer to constant'?

Yes I agree to the concept of 'constant pointer', but the 'pointer of concept' looks to be of no use.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
King
  • 183
  • 10
  • 1
    possible duplicate of [what is the difference between const int\*, const int \* const, int const \*](http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-int-const) – ClickRick Jun 21 '14 at 12:32
  • 1
    It means that you cannot use `ptr` to modify the thing it is pointing to. In this particular example it doesn't achieve anything since you have access to the thing pointed to via another name. But in general you do not have the other name available. For example: `void func(int const *ptr) { ...` More importantly, you don't know whether the thing pointed to is actually `const` or not. This code works on both `const int` and non-const `int`; whereas `void func(int *ptr)` only works on non-const ints. The benefit of the whole `const` setup is to help optimization and avoid writing to const data – M.M Jun 21 '14 at 12:38

1 Answers1

3

A pointer to constant should point to... a constant int. Your program compiles because you are pointing to tobepointed which is int.

If you declared it const int, then the only way to point it (without casts) would be with a const int*:

const int tobepointed = 10;
const int* ptr = &tobepointed;

And if you tried to create non-const pointer:

const int tobepointed = 10;
int* ptr = &tobepointed;

the compiler would complain:

error: invalid conversion from 'const int*' to 'int*'

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • yes, thanks a ton Jefffrey, So the concept of 'pointer to constant' exists as there is no way to refer to address of a constant variable. Did i get it ? – King Jun 21 '14 at 12:43