I myself am convinced that in a project I\'m working on signed integers are the best choice in the majority of cases, even though the value contained within can never be neg
Yes, i agree with Richard. You should never use 'int'
as the counting variable in a loop like those. The following is how you might want to do various loops using indices (althought there is little reason to, occasionally this can be useful).
for(std::vector::size_type i = 0; i < someVector.size(); i++) {
/* ... */
}
You can do this, which is perfectly defined behaivor:
for(std::vector::size_type i = someVector.size() - 1;
i != (std::vector::size_type) -1; i--) {
/* ... */
}
Soon, with c++1x (next C++ version) coming along nicely, you can do it like this:
for(auto i = someVector.size() - 1; i != (decltype(i)) -1; i--) {
/* ... */
}
Decrementing below 0 will cause i to wrap around, because it is unsigned.
That should never be an argument to make it the wrong way (using 'int'
).
The C++ Standard defines in 23.1 p5 Container Requirements
, that T::size_type
, for T
being some Container
, that this type is some implementation defined unsigned integral type. Now, using std::size_t
for i
above will let bugs slurp in silently. If T::size_type
is less or greater than std::size_t
, then it will overflow i
, or not even get up to (std::size_t)-1
if someVector.size() == 0
. Likewise, the condition of the loop would have been broken completely.