Changeable constants through a pointer
Written on March 29, 2009, by Milot Shala.

In my projects I very often declare constants because constants, are one of the important parts if you have low memory resources and you know for sure that you will not change the variable later, but somehow people refer to constants as not changeable of course you add more type safety in your code and it is also helpful for memory because you guarantee to your memory that this variable will not change and the memory will reserve a fixed size length for your variable, and it is very useful, but you still can change it (even that you declared it as not changeable) using a pointer which points to a memory address location on the constant variable as shown in the code below:

const int x = 0; // declare a constant with value of 0
int *px = &x; // get the constant variable memory address location
*px = 10; // assign value of 10 to x through the pointer which points to memory address of x
printf("%d\n",x); // print value of x which is 10 now!

But you can also prevent it from changing from the pointer using a constant pointer like in the code below:

const int x = 0; // declare a constant with value of 0
const int *px = &x; // get the constant variable memory address location but this time we have a const pointer
*px = 10; // assign value of 10 to x through the pointer which points to memory address of x
printf("%d\n",x); // print value of x which is 10 now!

And this will throw a compile-time error which will not allow you to compile your program because you are trying to assign a value in a read-only location.

IMO changing a constant in this way is very useful because you can always access it through a memory location address using a pointer and change it, but remember to not declare pointer as a constant.

  • http://www.gizmobooks.com GizmoBooks

    Hey Milot!

    Didn’t know you could change a constant like that! Thanks for the info.

    -Gizmo

  • http://codespartan.org/blog/ Milot Shala

    Gizmo,

    I was also surprised when I saw this happening.

blog comments powered by Disqus

697 views

© Copyright Phalanx Blogosphere - Powered by Wordpress - Phalanx logo is designed by Leopard Cana