In the Arduino language, if you write

long A = 90000; Serial.println(A); 

then everything works correctly, but if you write

 long A = 300*300; Serial.println(A); 

it outputs 24,464. And even if you write

 Serial.println(300*300); 

the result is the same. What could be the problem?

  • one
    Or maybe on your platform int 16-bit? 90000 - 24464 = 65536. - VladD
  • @VladD int 16 bit for arduino by default, checked with sizeof operator. Did I understand correctly that the result of the degeneration should fit into an int? It just works the same way, even if assigned to a variable of type float or double. - Timeon
  • one
    Just the result of multiplying an int by an int is exactly an int , so if it doesn't fit into an int , the high bytes are discarded. And the constant 90000, as indicated in the answer, is interpreted immediately as a long . - VladD
  • @VladD Thank you, now everything is clear - Timeon
  • You are welcome! Glad that helped. - VladD

1 answer 1

It looks like an expression

 long A = 300*300; ^^^^^^^^ 

computed as int , and an object of type int cannot contain the resulting value.

Write down as follows

 long A = ( long )300*300; 

or

 long A = 300l*300l; 

Regarding this initialization

 long A = 90000; 

then for an integer literal, the compiler defines the integer type that can hold this value.

According to standard C (6.4.4.1 Integer constants)

5 can be represented

And further in the table it is indicated that when the literal has no suffix, the type of the literal is sequentially chosen in the order int , long int , long long int .

  • It is strange that while long A = 90000; compiled as if 90000 intervenes in int . - VladD
  • @VladD The compiler defines a suitable type for the literal. This will not necessarily be an int type. - Vlad from Moscow
  • Hmm, and this is standard? - VladD
  • one
    @VladD I have shown this in my answer. - Vlad from Moscow
  • Wow, cool, did not know, thank you! - VladD