如何在C中修改const变量?
在C或C++中,我们可以使用常量变量。常数变量值初始化后不能更改。在本节中,我们将看到如何更改某些常量变量的值。
如果要更改常量变量的值,则会产生编译时错误。请检查以下代码以获得更好的主意。
示例
#include <stdio.h>
main() {
const int x = 10; //define constant int
printf("x = %d\n", x);
x = 15; //trying to update constant value
printf("x = %d\n", 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\n", x);
ptr = &x; //ptr points the variable x
*ptr = 15; //Updating through pointer
printf("x = %d\n", x);
}输出结果
x = 10 x = 15
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短