Why doesn't this code print same number? :
long long a, b; a = 2147483647 + 1; b = 2147483648; printf("%lld\n", a); printf("%lld\n", b);
I know that int variable's maximum number is 2147483647 because int variable is 4 byte. But as I know, long long variable is 8 byte, but why does that code act like that?
Compiler designers tend to to maximize the performance of int arithmetic, making it the natural size for the underlying processor or OS, and setting up the other types accordingly. But the use of long int , since int can be omitted, it's just the same as long by definition.
The code could be ran on a 16-bit platform with 32-bit long and 16-bit int on which the int would probably be faster - but not necessarily. On the other hand, on a native 32-bit platform which has 32-bit int and 64-bit long , the long could be faster - but not necessarily.
long int : -2,147,483,647 to 2,147,483,647.
Yes, you can add a long and an int just fine, and you'll end up with a long . The int undergoes a widening primitive conversion, as described in the Java Language Specification, specifically JLS8, §5.1. 2 .
2147483647 + 1
is evaluated as the sum of two ints
and therefore overflows.
2147483648
is too big to fit in an int
and is therefore assumed by the compiler to be a long
(or a long long
in MSVC). It therefore does not overflow.
To perform the summation as a long long
use the appropriate constant suffix, i.e.
a = 2147483647LL + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With