Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ int versus long

Tags:

c++

In C++, is there any benefit to using long over int?

It seems that long is the default word size for x86 and x86_64 architectures (32 bits on x86 and 64 bits on x86_64, while int is 32 bits on both), which should (theoretically) be faster when doing arithmetic.

The C++ standard guarantees that sizeof(int) <= sizeof(long), yet it seems that long is the default size on both 32-bit and 64-bit systems, so should long be used instead of int where possible when trying to write code that is portable over both architectures?

like image 264
Master of Puppets Avatar asked Jul 27 '12 06:07

Master of Puppets


2 Answers

long is guaranteed to be at least 32-bits whereas int is only guaranteed to be at least 16-bits. When writing a fully portable program you can use long where the guaranteed size of an int is not sufficient for your needs.

In practice, though, many people make the implicit assumption that int is larger than the standard guarantees as they are only targeting such platforms. In these situations it doesn't usually matter much.

int should be the "natural" size of a number for a system; in theory long might be more expensive but on many architectures operations on long are not more expensive even where long is actually longer than int.

like image 51
CB Bailey Avatar answered Sep 19 '22 04:09

CB Bailey


If you need integer types that will remain the same size across different platforms, you want the types in <stdint.h>.

For instance, if you absolutely need a 32-bit unsigned integer, you want uint32_t. If you absolutely need a 64-bit signed integer, you want int64_t.

like image 27
atomicinf Avatar answered Sep 20 '22 04:09

atomicinf