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
本页由热血青年 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.