Define

#define 允許在編譯程式前,為常數數值定義一個名字。當使用者在程式碼內使用新定義的名字時,編譯器會在編譯時將這些名字替換成該名字所代表的常數數值。因此並不會使用到額外的86Duino記憶體空間。

必須注意若是使用#define 來定義一個名字的數值後,再使用此名字宣告變數或常數時,編譯器會把此名字換成 #define 的數值而不會將此名字宣告為變數或常數。

一般來說,建議使用 const 關鍵字來定義常數而不使用 #define

86Duino 與 C 語言的語法定義相同:

語法


#define constantName value

注意 # 符號是不可省略的。

範例

#define ledPin 3
// 編譯器將在編譯時把任何使用到 ledPin 的地方,以 3 來替換掉。

提醒

在使用 #define 時不可在結尾加入分號。若是加入了也合乎語法,但可能在使用時產生錯誤。(不建議初學者使用)

#define ledPin 3; // 不建議這麼做

同樣,在 #define 內也不建議使用等號,亦可能產生未預期的錯誤。

#define ledPin = 3 // 不建議這麼做

See also

const
Constants


語法參考主頁面

本頁由熱血青年 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.