如何修改 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

更新于:2019-07-30

5K+ 浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.