What's the difference between long long and long
Solution 1
Going by the standard, all that's guaranteed is:
int
must be at least 16 bitslong
must be at least 32 bitslong long
must be at least 64 bits
On major 32-bit platforms:
int
is 32 bitslong
is 32 bits as welllong long
is 64 bits
On major 64-bit platforms:
int
is 32 bitslong
is either 32 or 64 bitslong long
is 64 bits as well
If you need a specific integer size for a particular application, rather than trusting the compiler to pick the size you want, #include <stdint.h>
(or <cstdint>
) so you can use these types:
int8_t
anduint8_t
int16_t
anduint16_t
int32_t
anduint32_t
int64_t
anduint64_t
You may also be interested in #include <stddef.h>
(or <cstddef>
):
size_t
ptrdiff_t
Solution 2
long long
does not exist in C++98/C++03, but does exist in C99 and c++0x.
long
is guaranteed at least 32 bits.
long long
is guaranteed at least 64 bits.
Solution 3
To elaborate on @ildjarn's comment:
And they both don't work with 12 digit numbers (600851475143), am I forgetting something?
The compiler looks at the literal value 600851475143
without considering the variable that you're assigning it to/initializing it with. You've written it as an int
typed literal, and it won't fit in an int
.
Use 600851475143LL
to get a long long
typed literal.
Comments
-
Hikari Iwasaki almost 2 years
What's the difference between long long and long? And they both don't work with 12 digit numbers (600851475143), am I forgetting something?
#include <iostream> using namespace std; int main(){ long long a = 600851475143; }
-
ildjarn almost 13 yearsMake that
long long a = 600851475143LL;
and it should work. -
Mahmoud Gabr almost 3 years@ildjarn Why would I need to to specify the format using the (LL) postfix, when I have already specified it with a (long long) when declaring the variable?
-
-
Hikari Iwasaki almost 13 yearswhat do you mean by the "long is either 32 or 64 bits"? Can it change its bits?
-
Joey Adams almost 13 years@Hikari Iwasaki: It depends on the target. For example, if you're compiling on Windows, it might be 32 bits, while on Linux x86-64, it might be 64 bits. Types don't change sizes at run-time.
-
Alexis Wilke over 2 yearsAnd g++ even has an
__int128
type, to extend the list...