-2

I have this piece of code..

#include <iostream>

int main()
{
        int r = 5;
        const int * rptr= &r;
        *rptr++; // undefined value (trash)
        *rptr=3; // error
        std::cout<<*rptr<<" "<<r<<std::endl;
        rptr = new int (6);
        std::cout<<*rptr<<" "<<r<<std::endl;


        return 0;
}

Why does it show me errors when I try to assign a new value to the constant integer which the pointer points to, but doesn't when I try to increment the value.
When I incremented *rptr it assigned an undefined value to it, so I tried to check if both are pointing to the same address and they do.

Here's the output of the previous code but without the line containing the error:

-1079235284 5
6 5

using g++4.8 on a Linux x86 machine

plus
  • 19
  • 1
  • 5
  • 4
    Because you don't have a *constant pointer*, you have a *pointer to constant* – Praetorian Feb 03 '15 at 17:55
  • Thats a `const int` you are declaring. Not a `const *`. – Captain Giraffe Feb 03 '15 at 17:55
  • Oh yeah sorry about saying constant *, I know that it's a pointer to a constant. but it allows me to increment the value of that constant int.. shouldn't it show me an error? – plus Feb 03 '15 at 17:58
  • @geekybedouin: You're incrementing the pointer (to point to an undefined location), not the object it points to. `(*rptr)++` would try to increment the object, and give an error. – Mike Seymour Feb 03 '15 at 18:02
  • `const`, not "constant". Though the words are obviously related, `const` means "read-only", while a *constant* is a literal like `42`, and a *constant expression* is an expression that can be evaluated at compile time. For example: `const int r = rand();`; `r` is `const`, but clearly not *constant*. – Keith Thompson Feb 03 '15 at 18:13
  • your comment is wrong, *rptr++ has defined value, which is 5 in your case – Slava Feb 03 '15 at 18:17

2 Answers2

6

Why does it show me errors when I try to assign a new value to the constant pointer

You'll get an error if you try to modify the value it points to (since you've declared it to be a pointer to a constant value); modifying the pointer is fine, since the pointer itself is not constant.

*rptr=3;               // error - attempt to modify constant value
rptr = new int (6);    // OK - modifies non-const pointer 

but doesn't when I try to increment the value.

You're not incrementing the value. That would be

(*rptr)++;

while your code is equivalent to

*(rptr++);

which increments the pointer, and dereferences its old value, but ignores the dereferenced value. Dereferenced it again after incrementing it, as you do later, gives undefined behaviour - you happen to see a garbage value, which is whatever happened to be in the next memory location, but in principle anything could happen.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

You're not incrementing the value here.. Check the Operator Precedence Table: here

geekybedouin
  • 549
  • 1
  • 11
  • 23