Search code examples
c++constantspoint-of-interest

const in body of C++ functions


I realized, what if i define const int into the body of c++ function and then use the address arithmetic to change the value of the constant( its on the stack, isn't it? ). i got this code:

const int a = 10;
int b = 100;

int * c = &b;
c++;

cout << "&a: " << &a << endl;
cout << " c: " << c << endl;


*c = 100500;

cout << " a: " << a << endl;
cout << "*c: " << *c << endl;

and i got this output

&a: 0x7ffff63866a8
c: 0x7ffff63866a8

 a: 10
*c: 100500

So, addresses are the same, but values are different. Can someone explain me this result? Thanks! p.s. i tried on GCC, Clang and VS


Solution

  • const int a = 10;
    int b = 100;
    

    OK.

    int * c = &b;
    

    OK, but silly and my bug-o-meter is starting to twiddle.

    c++;
    

    Bug-o-meter now in the yellow zone.

    cout << "&a: " << &a << endl;
    

    OK

    *c = 100500;
    

    Bug-o-meter pegged. Undefined Behavior invoked. World explodes, you get fired.

    c++ moves the pointer to the next int in memory. The pointer math is OK, but all you can use c for at this point is to compare the pointer to another pointer. You can't dereference the pointer in any way. But that's what you do when you try to assign through it.

    What happens next is irrelevant and, honestly, misleading. You think that c now points to the same memory as b, and maybe it does. But it's only through Undefined Behavior that this happened. You might also think that the value of *c is what you expect it to be, but this result is false. Maybe it is, maybe it isn't. You shattered the vial when you opened the box -- the cat is dead. And so is your program.

    And by the way, if what you're trying to do is find a way to cheat the compiler so that you can change a const, don't -- it is strictly forbidden to change a const by any means.

    There is a const_cast in C++, but that is also not a mechanism that you can use to change a const.