Home  >  Article  >  Backend Development  >  How to modify a const variable in C?

How to modify a const variable in C?

WBOY
WBOYforward
2023-08-30 16:33:091292browse

How to modify a const variable in C?

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.

Example

#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);
}

Output

[Error] assignment of read-only variable &#39;x&#39;

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.

Example

#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);
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete