Home > Backend Development > C++ > body text

How to modify a const variable in C?

WBOY
Release: 2023-08-30 16:33:09
forward
1371 people have browsed it

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);
}
Copy after login

Output

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

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);
}
Copy after login

Output

x = 10
x = 15
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!