const

const 是常數的意思,它可以將變數限定成只能讀取其數值。這代表被限定的變數只能被讀取而不能去改變它的數值;如果你嘗試去更改它,編譯器會產生錯誤訊息來提醒你不可以改變 const 變數。

以 const 定義之常數也會遵循 變數作用範圍 的規則。由於使用 #define 定義常數時有較多需注意的地方,因此一般建議以 const 來定義常數會比用 #define 還要好。

範例

const float pi = 3.14;
float x;

// ....

x = pi * 2;    // 這邊可以使用 const 常數作為運算使用

pi = 7;        // 不合法,你不能把值寫入 const 常數中

使用 #define 還是 const?

你可以用 const#define 去創建一個數字或字串常數,但若是陣列,你僅可使用 const。一般來說用 const 定義常數會比用 #define 還要好。

See also

#define
volatile


語法參考主頁面

本頁由熱血青年 LBU 譯自英文版。

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.