CONST keyword does not make the variable constant! HOW?

Table of contents

No heading

No headings in the article.

In this post, we will discuss a workaround that allows us to change the value of a constant variable. The trick is to assign the address of the constant variable to a pointer and then modify its value by dereferencing the pointer.

In the below code, we have declared a constant integer variable x and initialized it to 5. Next, we declare a pointer variable ptr of type integer and assign the address of x to it. Since ptr is not a constant pointer, we can modify the value it points to. Therefore, we dereference the pointer and assign a new value 50 to x. Finally, we print the value of x.

The output of the code will be The value of x is 50.

However, it is important to note that this is not a recommended practice and should be avoided as much as possible. Changing the value of a constant variable goes against the principle of const correctness and can lead to unexpected behavior in your code. It is always better to declare a variable as non-const if you plan to modify its value later.

#include <stdio.h>
int main() {
   const int x = 5;
    int *ptr = (int*)&x; // cast away const and store address of x in ptr

   *ptr = 50;       // change the value of x to 50 by dereferencing ptr        
   printf("The value of x is %d\n", x);
   return 0;
}