How to Use 'U' and 'L' formatters in Arduino?

ArduinoHardwareSoftware & Coding

When going through Arduino codes, you may come across some numbers which are followed by either a U or an L or both (or in small caps, u and l). These are formatters, which force integer constants to be of a specific format. U forces an integer constant to be of the unsigned data format, while L forces the integer constant to be of the long data format.

These formatters can be used when defining variables, as well as using some integer values directly in a formula.

Example

int a = 33u;
# define b 33ul
int c = a*1000L;

All of the above lines compile fine. Of course, one may wonder what is the point of using an integer data type if you were to restrict the data type to an unsigned int (like in the first example, int a = 33u). There isn't any point. They just convey intent (that you want Arduino and the reader to treat them like an unsigned int or a long). The type of the variable remains an int.

Example

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:
}

The Serial Monitor will print -12 (meaning that a is still of type int; unsigned int can't take negative values).

After the above example, you may be wondering if there is any point of specifying the U and L formatter at all. Well, the following example will give you a use case.

Example

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:
}

The Serial Monitor prints only "Statement 1 is true". This is because in the second case (x < 5U), by using the U formatter, we converted the arithmetic to unsigned arithmetic. And unsigned equivalent of -3 will be greater than 5. However, if you rewrite the above code as follows −

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:
}

Then, both the statements are printed. This shows that type supersedes the formatter.

raja
Published on 24-Jul-2021 14:16:22
Advertisements