Is it a good habit to use "string::size_type" as an index, rather than int?
Fro, eg
Code:string::size_type index; //not "int index"
cout<<str[index];
Is it a good habit to use "string::size_type" as an index, rather than int?
Fro, eg
Code:string::size_type index; //not "int index"
cout<<str[index];
Yes, if you're using it as an index into a string.
What's the catch to use int?
It will be very rare that it actually matters in practice. The potential problem is that int might not hold all the possible values that can be used as indexes in the string. The size_type typedef is meant to be used because it guarantees that it won't be too big or too small for the indexes in the string.
The biggest concern is if your string is _REALLY_ big, the signedness of int halfes the size that the string could be. [not to mention that 64-bit machines may have 32-bit int, and 64-bit sizetype - allowing strings to be longer than what can be represented in a 32-bit integer]
The problem with comparing a signed integer with an unsigned quantity is that you need to make sure you do it right way around - the compiler will most likely warn about unsigned and signed being compared. A signed value has half the positive range (because one bit is the sign) compared to an unsigned value, but also, if you convert a LARGE unsigned to a signed value, it will become negative, which if it's truly an unsigned quantity (such as the length of a string), it is obviously not smaller than the largest positive value that a signed integer can hold, but a negative value produced by such a conversion is smaller! This could potentially lead to all sorts of confusing and strange results, not to mention strange bugs.
Now, most people have strings that are a few dozen to a few kilobytes in size - I was debugging a problem with a collegues (commercial) software at work the other day. It was caused by a string being read from a file, where the string was bigger than what the software could cope with - a bit more than 1 kb strings were allowed, but the file being read had MUCH larger strings. This was not OUR software, but it was reading one of OUR files.
But the signed/unsigned problem is unlikely to happen until strings are at a very minimum 32K long, and on modern OS's and machines, more likely to happen at 2G in length - that's a MASSIVE string.
--
Mats
Basically, it's good to avoid compiler warnings.