What's the difference between int
and long
in C++ since both:
sizeof(int)
... and
sizeof(long)
return 4
?
What's the difference between int
and long
in C++ since both:
sizeof(int)
... and
sizeof(long)
return 4
?
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.
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.
You're on a 32-bit machine. On my 64-bit machine, sizeof(int) == 4
, but sizeof(long) == 8
.
They're different types - sometimes the same size as each other, sometimes not.
(In the really old days, sizeof(int) == 2
and sizeof(long) == 4
- though that might have been the days before C++ existed, come to think of it.)
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.
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, but normally implemented as an extension in C++.)