What data type should be used for a general-purpose integer in C++?
The obvious answer is int
, and this made sense in old times where it was commonly 16-bit on 16-bit machines and 32-bit on 32-bit machines. But now 64-bit code is becoming more common, but int
is often 32-bit on those compilers. So we can't assume int
is necessarily the "fastest" or largest type for that system any more.
Another problem is propagation of 64-bit values from the size of data structures and files. I know you can store these values in a 32-bit int and get away with it, if the size doesn't get too big. But I want to write code which can handle the maximum size of data, if that's what the user wants. I don't want my code to die if the user opens a 5gb file and wants the whole thing in memory, because the size is stored in an int
somewhere. 16+gb ram systems will be the norm someday, and I want my code to still work.
I know that there are types such as vector<T>::size_type
to store that data. But what if size data can come from several different container and stream types? Should I use size_t
for all integers which may store size information?
So I'm forced to conclude I should use the size_t
data type (or signed equivalent, I can live with a maximum of 9,223,372,036,854,775,807 bytes per data structure for now), and not int
, for general-purpose use, but this is not what I observe in practice, where int
is still commonly used.
What integer data type should I use for general-purpose calculations and what are the technical reasons for doing so?