Monthly Archives: May 2023

Unsigned Int, Mathematical operations and pitfalls in Arduino or C

Let’s consider the below code:


unsigned long startTime = 1940, stopTime = 0;

if( (stopTime - startTime) > 5000ul)
{
Serial.println("Hello World!");
}

Will this say Hello World?

Yes, it will. If this sounds new or surprising to you, please continue reading below.

Note the variables have been defined as unsigned long. So the result of mathematical operations will also be in unsigned value. Hence though the result of the operation apparently looks to be -1940 but in practise it will be 4294965356

And thus the comparison in the if() will evaluate to true.