We know in C++ programming language, int
type occupies 4 bytes, while long
type occupied 8 bytes, and could be verified via following code snippet.
cout << "sizeof(int) = " << sizeof(int) << endl;
cout << "sizeof(long) = " << sizeof(long) << endl;
>>> sizeof(int) = 4
>>> sizeof(long) = 8
Thus, we can further deduce the maximum number that can be represented by int
type is 2^31-1, if we increase this by 1, it would raise integer overflow issue.
int a = (1<<31)-1;
int b = a+1;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
>>> a = 2147483647
>>> b = -2147483648
In order to prevent the potential overflow issue, we can use long
type, as it supports much wider range compared with int
type from previous test result. However, I found following style would still fail due to integer overflow why coding in leetcode.
long c = a+1;
long d = (long)(a+1);
And currently I have to write it in a more tedious way.
long e = c;
e = e+1;
Does anyone know why this happens, help explain and how can we resolve this via a more neat way? Thanks.