如何在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短