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?
What is faster and what is not is something that is becoming harder to predict every day. The reason is that processors are no more “simple” and with all the complex dynamics and algorithms behind them the final speed may follow rules that are totally counter-intuitive.
The only way out is to just measure and decide. Also note that what is faster depends on the little details and even for compatible CPUs what is an optimization for one can be a pessimization for the other. For very critical parts some software just tries and checks timings for different approaches at run time during program initialization.
That said, as a general rule the faster integer you can have is
int. You should use other integers only if you need them specifically (e.g. iflongis larger and you need the higher precision, or ifshortis smaller but enough and you need to save memory).Even better if you need a specific size then use a fixed standard type or add a
typedefinstead of just sprinkling aroundlongwhere you need it. This way it will be easier to support different compilers and architectures and also the intent will be clearer for whoever is going to read the code in the future.