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.