Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are C++ int and long types both 4 bytes?

Many sources, including Microsoft, reference both the int and long type as being 4 bytes and having a range of (signed) -2,147,483,648 to 2,147,483,647. What is the point of having a long primitive type if it doesn't actually provide a larger range of values?

like image 433
hodgesmr Avatar asked Nov 15 '12 13:11

hodgesmr


People also ask

Why size of int is 4 bytes in C?

The fact that an int uses a fixed number of bytes (such as 4) is a compiler/CPU efficiency and limitation, designed to make common integer operations fast and efficient.

Why are int and long 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 int always 4 bytes?

Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.

Does int use 2 bytes or 4 bytes?

Most of the textbooks say integer variables occupy 2 bytes.


1 Answers

The only things guaranteed about integer types are:

  1. sizeof(char) == 1
  2. sizeof(char) <= sizeof(short)
  3. sizeof(short) <= sizeof(int)
  4. sizeof(int) <= sizeof(long)
  5. sizeof(long) <= sizeof(long long)
  6. sizeof(char) * CHAR_BIT >= 8
  7. sizeof(short) * CHAR_BIT >= 16
  8. sizeof(int) * CHAR_BIT >= 16
  9. sizeof(long) * CHAR_BIT >= 32
  10. sizeof(long long) * CHAR_BIT >= 64

The other things are implementation defined. Thanks to (4), both long and int can have the same size, but it must be at least 32 bits (thanks to (9)).

like image 179
Griwes Avatar answered Oct 10 '22 20:10

Griwes