1

When I was trying to figure out top-level const and const_cast, I wrote some code as follows.

int main()
{
    // m is a top-level const
    const int m = 10;

    // this is an undefined behavior according to *Primer c++*
    // but I still compile and run this without warning. 
    int *q = const_cast<int *>(&m);
    (*q)++;

    //Then I print the address and the value
    cout<< "the value  of address "<< q <<" is "<< *q <<endl;
    cout<< "the value  of address "<< &m <<" is "<< m <<endl;
    return 0;
}

The print result makes me confused.

the value  of address 0x7ffee6a43ad8 is 11
the value  of address 0x7ffee6a43ad8 is 10

Is that one of the undefined Behaviours? What really happened when I do "(*q)++"?

Thanks in advance

Sunset
  • 13
  • 3

2 Answers2

2

Note that your code doesn't do *q++, it does (*q)++.

With *q++ you increment the pointer. With (*q)++ you increment what it's pointing at.

That is all well and good, except that q is pointing to a constant value. Attempting to modify a constant value is, indeed, undefined behavior.

If you instead did *q++ and incremented the pointer, then you would not modify the constant value, so that will be okay. On the other hand, it no longer point to a valid object and you will instead have UB when you dereference q when printing the value it points to.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Sorry about the typo which I have corrected above. Actually what I don't know is the behaviour of (*q)++. – Sunset Mar 05 '18 at 07:51
  • @Sunset As I said in my answer, `(*q)++` attempt to increment what `q` is pointing at. Which is UB since it's pointing to a constant value. – Some programmer dude Mar 05 '18 at 08:32
0

Is that one of the undefined Behaviours?

Yes. You really have two lines each of which can cause undefined behavior.

int *q = const_cast<int *>(&m);

and

(*q)++;

In the first one, you are using const_cast to remove the const-ness of the object that a pointer points to when that object was created with the const qualifier.

In the second one, you are modifying the value of const object.

What really happened when I do "(*q++)"?

You'll have to look at assembly code to figure out what the compiler does with it. It can do anything it wants to. We can't fault it for doing what it did.

R Sahu
  • 204,454
  • 14
  • 159
  • 270