Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does long long 2147483647 + 1 = -2147483648? [duplicate]

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?

like image 522
Hoseong Jeon Avatar asked May 05 '20 23:05

Hoseong Jeon


People also ask

Why are long and int the same size?

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.

Is Long Long faster than int?

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.

How many numbers can long int store?

long int : -2,147,483,647 to 2,147,483,647.

Can int be added to long?

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 .


1 Answers

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; 
like image 166
Paul Sanders Avatar answered Oct 02 '22 19:10

Paul Sanders