Arduino 中 #define 和 const 的区别

arduinohardwaresoftware & coding更新于 2026/1/12 9:22:17

如果您有丰富的 Arduino 编程经验,您就会知道定义常量有两种方法。

#define

一种方法是使用 #define,例如

#define const_name 3

const

另一种方法是使用 const 关键字,例如

const int var_name = 3;

#define 和 const 的区别

#define 就像一个占位符。Arduino 编译器会在编译时将所有引用此常量的地方替换为其值。这意味着使用 #define 定义的值不会占用任何程序空间。

另一方面,使用 const 定义的变量只是普通变量,其值无法更改。它们占用程序内存空间,并且具有类型(这在很多情况下都很有利)。

通常,在定义常量时,优先使用 const 而不是 #define。


相关文章