How to modify a const variable in C?

CServer Side ProgrammingProgramming

In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization. In this section we will see how to change the value of some constant variables.

If we want to change the value of constant variable, it will generate compile time error. Please check the following code to get the better idea.

Example

#include <stdio.h>
main() {
   const int x = 10; //define constant int
   printf("x = %d\n", x);
   x = 15; //trying to update constant value
   printf("x = %d\n", x);
}

Output

[Error] assignment of read-only variable 'x'

So this is generating an error. Now we will see how we can change the value of x (which is a constant variable).

To change the value of x, we can use pointers. One pointer will point the x. Now using pointer if we update it, it will not generate any error.

Example

#include <stdio.h>
main() {
   const int x = 10; //define constant int
   int *ptr;
   printf("x = %d\n", x);
   ptr = &x; //ptr points the variable x
   *ptr = 15; //Updating through pointer
   printf("x = %d\n", x);
}

Output

x = 10
x = 15
raja
Published on 26-Apr-2019 12:46:46
Advertisements