I checked the document that long= int64 has range more than 900,000,000,000,000
Here is my code:
int r = 99;
long test1 = r*r*r*r*r;
at runtime it gives me 919,965,907 instead of the correct 9,509,900,499.
another test
long test2 = 99*99*99*99*99;
It refuses to compile, saying integer overflow.
But if i do this
long test3 = 10100200300;
This works fine.
The problem is that the literal “99” is being treated as an int. If you add “L” it will treat it as a long. To fix your compilation problem:
And to fix the “incorrect result” caused by integer overflow:
The key point is that the expression to the right of the “=” is evaluated before the assignment to
long ris done.There are other literal suffixes you might be interested in:
@m.edmonson, regarding your question about why it comes out to 919965907. What’s happening, is that the value is “wrapping” around int.MaxValue. You can see this with a little test program:
What is meant by “wrapping around”? When you exceed
int.MaxValueby 1, the value “goes back” toint.MinValue.This is a bit simplistic; if you search for “integer overflow” you will get a better explanation. It’s worth understanding how integers (and other numeric types) are represented with 32 bits:
http://en.wikipedia.org/wiki/Signed_number_representations