Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between long and int data types [duplicate]

Considering that the following statements return 4, what is the difference between the int and long types in C++?

sizeof(int) sizeof(long) 
like image 626
Alex Avatar asked May 22 '09 22:05

Alex


People also ask

What is the difference between long and int data types?

The difference between int and long is that int is 32 bits in width while long is 64 bits in width.

What is difference between long long and long long int?

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 .

Should I use long or int?

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 .


2 Answers

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.

like image 127
Paul Sonier Avatar answered Sep 26 '22 08:09

Paul Sonier


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.)

like image 27
Dan Olson Avatar answered Sep 25 '22 08:09

Dan Olson