如何修改 C 中的 const 变量?
在 C 或 C++ 中,我们可以使用常量变量。常量变量的值在其初始化后不能更改。在本节中,我们将看到如何更改某些常量变量的值。
如果我们要更改常量变量的值,它将生成编译时错误。请检查以下代码以获得更好的理解。
示例
#include <stdio.h>
main() {
const int x = 10; //define constant int
printf("x = %d
", x);
x = 15; //trying to update constant value
printf("x = %d
", x);
}输出
[Error] assignment of read-only variable 'x'
所以这会生成一个错误。现在,我们将看到如何更改 x(它是一个常量变量)的值。
要更改 x 的值,我们可以使用指针。一个指针将指向 x。现在,如果我们使用指针更新它,它不会生成任何错误。
示例
#include <stdio.h>
main() {
const int x = 10; //define constant int
int *ptr;
printf("x = %d
", x);
ptr = &x; //ptr points the variable x
*ptr = 15; //Updating through pointer
printf("x = %d
", x);
}输出
x = 10 x = 15
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP