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?
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With