This question already has an answer here:
Considering that the following statements return 4
, what is the difference between the int
and long
types in C++?
sizeof(int)
sizeof(long)
This question already has an answer here:
Considering that the following statements return 4
, what is the difference between the int
and long
types in C++?
sizeof(int)
sizeof(long)
The long must be at least the same size as an int, and possibly, but not necessarily, longer.
On common 32-bit systems, both int and long are 4-bytes/32-bits, and this is valid according to the C++ spec.
On other systems, both int and long long may be a different size. I used to work on a platform where int was 2-bytes, and long was 4-bytes.
On platforms where they both have the same size the answer is nothing. They both represent signed 4 byte values.
However you cannot depend on this being true. The size of long and int are not definitively defined by the standard. It's possible for compilers to give the types different sizes and hence break this assumption.
A typical best practice is not using long/int/short directly. Instead, according to specification of compilers and OS, wrap them into a header file to ensure they hold exactly the amount of bits that you want. Then use int8/int16/int32 instead of long/int/short. For example, on 32bit Linux, you could define a header like this
You're on a 32-bit machine or a 64-bit Windows machine. On my 64-bit machine (running a Unix-derivative O/S, not Windows),
sizeof(int) == 4
, butsizeof(long) == 8
.They're different types — sometimes the same size as each other, sometimes not.
(In the really old days,
sizeof(int) == 2
andsizeof(long) == 4
— though that might have been the days before C++ existed, come to think of it. Still, technically, it is a legitimate configuration, albeit unusual outside of the embedded space, and quite possibly unusual even in the embedded space.)From this reference:
Also, this bit:
The guarantees the standard gives you go like this:
So it's perfectly valid for
sizeof (int)
andsizeof (long)
to be equal, and many platforms choose to go with this approach. You will find some platforms whereint
is 32 bits,long
is 64 bits, andlong long
is 128 bits, but it seems very common forsizeof (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.)