Considering that the following statements return 4
, what is the difference between the int
and long
types in C++?
sizeof(int) sizeof(long)
The difference between int and long is that int is 32 bits in width while long is 64 bits in width.
long and long int are identical. So are long long and long long int . In both cases, the int is optional. As to the difference between the two sets, the C++ standard mandates minimum ranges for each, and that long long is at least as wide as long .
Long is the Object form of long , and Integer is the object form of int . The long uses 64 bits. The int uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1). You should use long and int , except where you need to make use of methods inherited from Object , such as hashcode .
From this reference:
An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease.
Also, this bit:
On many (but not all) C and C++ implementations, a long is larger than an int. Today's most popular desktop platforms, such as Windows and Linux, run primarily on 32 bit processors and most compilers for these platforms use a 32 bit int which has the same size and representation as a long.
The guarantees the standard gives you go like this:
1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)
So it's perfectly valid for sizeof (int)
and sizeof (long)
to be equal, and many platforms choose to go with this approach. You will find some platforms where int
is 32 bits, long
is 64 bits, and long long
is 128 bits, but it seems very common for sizeof (long)
to be 4.
(Note that long long
is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)
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