Multiplication error in Arduino

I guys, I'm encountering a very strange problem with multiplication in Arduino. See the routine below. Has anyone seen anything like this?

void setup() { Serial.begin(115200);

unsigned long Id_Digital = 0; Id_Digital = 1*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 10000 Id_Digital = 2*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 20000 Id_Digital = 3*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 30000 Id_Digital = 4*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 4294941760 Id_Digital = 5*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 4294951760 Id_Digital = 6*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 4294951760 Id_Digital = 7*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 4464 Id_Digital = 8*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 14464 Id_Digital = 9*10000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 24464 Id_Digital = 1*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 100000 Id_Digital = 2*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 200000 Id_Digital = 3*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 300000 Id_Digital = 4*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 400000 Id_Digital = 5*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 500000 Id_Digital = 6*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 600000 Id_Digital = 7*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 700000 Id_Digital = 8*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 800000 Id_Digital = 9*100000; Serial.println(Id_Digital); // resultado na tela: Id_Digital = 900000 } void loop() { } .

4 and 10000 are both 16 bit signed int's for the compiler.

the multiplication of 2 numbers takes the largest of the two types as result. So that is 16 bit signed int.

40000 does not fit in an 16 bit int so it wraps around becoming minus 7000 something .

This number is expanded to 32 bit when assigned to ID_digital creating an UNsigned representation of that number giving a very large number.

IN the second loop the compiler sees that 100000 is a 32 bit int. so the result of the multiplication is a 32 bit int.

You can enforce datatype seen by the compiler this way - Id_Digital = 1*10000UL; // THe UL means Unsigned Long.

Thank you my friend, problem solved. 3 hugs.