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