如何在Arduino中使用“U”和“L”格式化符?
在浏览 Arduino 代码时,您可能会遇到一些后面跟着 **U** 或 **L** 或两者(或小写 **u** 和 **l**)的数字。这些是 **格式化符**,它们强制整数常量采用特定的格式。**U** 强制整数常量采用无符号数据格式,而 **L** 强制整数常量采用长整数数据格式。
这些格式化符可以在定义变量时使用,也可以在公式中直接使用一些整数值。
示例
int a = 33u; # define b 33ul int c = a*1000L;
以上所有代码都能正常编译。当然,有人可能会想知道,如果您要将数据类型限制为无符号 int(如第一个示例 **int a = 33u**),那么使用整数数据类型的意义何在。其实没有意义。它们只是传达意图(即您希望 Arduino 和读者将它们视为无符号 int 或长整数)。变量的类型仍然是 int。
示例
int a = 33u;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Hello");
a = a-45;
Serial.println(a);
}
void loop() {
// put your main code here, to run repeatedly:
}串口监视器将打印 **-12**(表示 a 仍然是 int 类型;无符号 int 不能取负值)。
在上述示例之后,您可能想知道是否根本有必要指定 **U** 和 **L** 格式化符。好吧,下面的示例将为您提供一个用例。
示例
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Hello");
int x = -3;
if(x < 5){
Serial.println("Statement 1 is true");
}
if(x < 5U){
Serial.println("Statement 2 is true");
}
}
void loop() {
// put your main code here, to run repeatedly:
}串口监视器仅打印“**语句 1 为真**”。这是因为在第二种情况下(x < 5U),通过使用 U 格式化符,我们将算术运算转换为无符号算术运算。-3 的无符号等价物将大于 5。但是,如果您将上述代码重写为以下内容:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Hello");
int x = -3;
int a = 5;
int b = 5U;
if(x < a){
Serial.println("Statement 1 is true");
}
if(x < b){
Serial.println("Statement 2 is true");
}
}
void loop() {
// put your main code here, to run repeatedly:
}那么,这两个语句都将被打印。这表明 **类型** 优先于 **格式化符**。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP