In C or C, we can use constant variables. The value of a constant variable cannot be changed after initialization. In this section we will see how to change the value of some constant variables.
If we want to change the value of a constant variable, a compile-time error will occur. Please check the following code to get a better idea.
#include <stdio.h> main() { const int x = 10; //define constant int printf("x = %d</p><p>", x); x = 15; //trying to update constant value printf("x = %d</p><p>", x); }
[Error] assignment of read-only variable 'x'
So there is an error here. Now we will see how to change the value of x (it is a constant variable).
To change the value of x, we can use pointers. A pointer will point to x. Now updating it using the pointer does not generate any errors.
#include <stdio.h> main() { const int x = 10; //define constant int int *ptr; printf("x = %d</p><p>", x); ptr = &x; //ptr points the variable x *ptr = 15; //Updating through pointer printf("x = %d</p><p>", x); }
x = 10 x = 15
The above is the detailed content of How to modify a const variable in C?. For more information, please follow other related articles on the PHP Chinese website!