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

How to modify a const variable in C?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-08-30 16:33:09
forward
1456 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
Latest Issues
双语言或多语言网站怎么做?
From 1970-01-01 08:00:00
0
0
0
C语言计算顺序问题
From 1970-01-01 08:00:00
0
0
0
Linux下一道C语言的经典面试题
From 1970-01-01 08:00:00
0
0
0
linux - 一道C语言printf的经典题目
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template