如何在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