-2

How is it possible that the value of *p and the value of DIM are different but the have the same address in memory?

const int DIM=9;
const int *p = &DIM;

* (int *) p = 18;     //like const_cast

cout<< &DIM <<"    "<< p << '\n';
cout << DIM << "   " << *p << '\n';

3 Answers3

2

You're changing the value of a const variable, which is undefined behavior. Literally anything could happen when you do this, including your program crashing, your computer exploding, ...

If a variable is supposed to change, don't make it const. The compiler is free to optimise away accesses to const variables, so even if you found a successful way to change the value in memory, your code might not even be accessing the original memory location.

James M
  • 18,506
  • 3
  • 48
  • 56
  • Thanks you! I got it! But i was testing const_cast limit, and is a little bit strange to see two different values in the same memory address – Riccardo Torrisi Feb 22 '16 at 00:55
2

It is a compiler optimization. Given that DIM is a constant, the compiler could have substituted its known value.

Marco Altieri
  • 3,726
  • 2
  • 33
  • 47
0

The code below does what you meant to do... as mentioned in other posts, if you mean to change the value of an variable, do not define it as const

#include <stdio.h>

int main()
{
    int d= 9;
    int *p_d=&d;

    *p_d=18;

    printf("d=%d\np_d=%d\n",d,*p_d);
    return 0;
}

This code prints

d=18
p_d=18
fnisi
  • 1,181
  • 1
  • 14
  • 24
  • Yes, i knew.. I was testing how compiler interpret a const-cast when pointer and variable are defined const.. And i didn't understand how was possibile that the programma return two differenti values that may ne in the same address – Riccardo Torrisi Feb 22 '16 at 01:07