Arduino arithmetic quirk

long bigvalue;
bigvalue = 400*400;

You’d expect bigvalue to hold 16000 right? No. Apparently arithmetic operation are done using the data type of the operand. So if you do any arithmetic operation (+-*/) that exceeds what the operand data type can hold, for example integer {+32767,-32768} you’d get some random overflown garbage result, even if the variable to hold the result is capable of containing it.

A workaround is to put the constant into a variable compatible with the result. Like

long bigvalue;
long bye = 400;
bigvalue = 400*bye;

The compiler will use the larger data type if mixed data types are used in an arithmetic operation, and in the above case produce the correct result.

Never see. Never know.

Leave a Comment

Your email address will not be published. Required fields are marked *