Variables bug

Hi! I have a situation I would like to report. When I define and initialize a variable like (for instante)

unsigned long interval= 420000;

It is different from doing:

unsigned long interval= 1000607;

If I print the variable interval to Serial, the first prints correctly, the second prints something like:


Is this a recognized bug?


unsigned long interval= 1000UL*60UL*7UL; And now?

Doing a lot of that millisecond to second conversion in your program? If the first variable is long, it will force the expression to long:

unsigned long interval= 1000UL*60*7;

so you can create a constant

const unsigned long MS_PER_S = 1000;
unsigned long interval= 60 * 7 *MS_PER_S;

which also increases the self documention level of the code. Or you can even:

const unsigned long MS_PER_S = 1000;
const unsigned long SECS_PER_MIN = 60;
unsigned long interval= 7 * SECS_PER_MIN * MS_PER_S;

unsigned long interval= 1000607;

The compiler defaults to doing the math with 16-bit integers, then it converts the result to a 32-bit (long) integer. The result of the multiplication is too large to fit in a 16-bit integer, so you don't get the result you expect. As the previous replies pointed out, by specifying at least one of the numbers as an unsigned long, that tells the compiler to do the math using 32-bit unsigned integers.

It's not so much of a problem on 32 or 64 bit machines that use larger int types, but the operation is the same.

Thank you KnownAsAWOL and aarg. I'll keep it in mind, but, nevertheless (at least for me) it's strange the approach needed...

Regards :slight_smile: