Some time ago I posted a short note about this kind of issues on my blog and the short answer is:
Always use proper C++ integer types
Long answer:
When programming in C++, it’s a good idea to use proper integer types relevant to particular context. A little bit of strictness always pays back. It’s not uncommon to see a tendency to ignore the integral types defined as specific to standard containers, namely size_type. It’s available for number of standard container like std::string or std::vector. Such ignorance may get its revenge easily.
Below is a simple example of incorrectly used type to catch result of std::string::find function. I’m quite sure that many would expect there is nothing wrong with the unsigned int here. But, actually this is just a bug. I run Linux on 64-bit architecture and when I compile this program as is, it works as expected. However, when I replace the string in line 1 with abc, it still works but not as expected :-)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "a:b:c"; // "abc" [1]
char delim = ':';
unsigned int pos = s.find(delim);
if(string::npos != pos)
{
cout << delim << " found in " << s << endl;
}
}
Fix is very simply. Just replace unsigned int with std::string::size_type. The problem could be avoided if somebody who wrote this program took care of use of correct type. Not to mention that the program would be portable straight away.
I’ve seen this kind of issues quite many times, especially in code written by former C programmers who do not like to wear the muzzle of strictness the C++ types system enforces and requires. The example above is a trivial one, but I believe it presents the root of the problem well.
I recommend brilliant article 64-bit development written by Andrey Karpov where you can find a lot more on the subject.
Best Answer
These are for platform-independence.
size_t
is, by definition, the type returned bysizeof
. It is large enough to represent the largest object on the target system.Not so many years ago, 32 bits would have been enough for any platform. 64 bits is enough today. But who knows how many bits will be needed 5, 10, or 50 years from now?
By writing your code not to care -- i.e., always use
size_t
when you mean "size of an object" -- you can write code that will actually compile and run 5, 10, or 50 years from now. Or at least have a fighting chance.Use the types to say what you mean. If for some reason you require a specific number of bits (probably only when dealing with an externally-defined format), use a size-specific type. If you want something that is "the natural word size of the machine" -- i.e., fast -- use
int
.If you are dealing with a programmatic interface like
sizeof
orstrlen
, use the data type appropriate for that interface, likesize_t
.And never try to assign one type to another unless it is large enough to hold the value by definition.