Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I notice ints and longs have the same size. Why?

Tags:

c++

Just noticed this on OSX and I found it curious as I expected long to be bigger than int. Is there any good reason for making them the same size?

like image 952
Daniel Avatar asked May 03 '09 15:05

Daniel


People also ask

Why is long and int the same size?

Compiler designers tend to to maximize the performance of int arithmetic, making it the natural size for the underlying processor or OS, and setting up the other types accordingly. But the use of long int , since int can be omitted, it's just the same as long by definition.

Is Long always bigger than int?

"a long in C/C++ is the same length as an int." Not always. The C++ standard specifies that an int be the "natural" size for the processor, which may not always be as big as a long . The standard also guarantees that a long is at least as long as an int , so the fact that they are equal sizes are not always guaranteed.

Are ints and floats the same size?

They are totally different - typically int is just a straightforward 2's complement signed integer, while float is a single precision floating point representation with 23 bits of mantissa, 8 bits exponent and 1 bit sign (see http://en.wikipedia.org/wiki/IEEE_754-2008).

What is the difference between long and int?

An int is a 32-bit integer; a long is a 64-bit integer. Which one to use depends on how large the numbers are that you expect to work with. int and long are primitive types, while Integer and Long are objects.


2 Answers

This is a result of the loose nature of size definitions in the C and C++ language specifications. I believe C has specific minimum sizes, but the only rule in C++ is this:

1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long)

Moreover, sizeof(int) and sizeof(long) are not the same size on all platforms. Every 64-bit platform I've worked with has had long fit the natural word size, so 32 bits on a 32-bit architecture, and 64 bits on a 64-bit architecture.

like image 151
Tom Avatar answered Nov 05 '22 15:11

Tom


  • int is essentially the most convenient and efficient integer type
  • long is/was the largest integer type
  • short is the smallest integer type

If the longest integer type is also the most efficient, the int is the same as long. A while ago (think pre-32 bit), sizeof(int) == sizeof(short) on a number of platforms since 16-bit was the widest natural integer.

like image 24
D.Shawley Avatar answered Nov 05 '22 14:11

D.Shawley