I had a strange error in my program and it came down to a (for me) unexpected behaviour when doing a substraction between an int and a vector::size_type. Here is a simple example:
#include <iostream>
#include <vector>
typedef std::vector<double> state_type;
int n = 1;
int main() {
state_type::size_type i = 0;
std::cout << i - n << std::endl;
}
I expected this program to prints -1, but it prints (compiled with icc 14.0.1 under 64bit Linux) :
18446744073709551615
My current explanation is that size_type is unsigned and this leads to some weird (?) conversion ? I only found this error after a long time and I am very surprised this happens. Now my question is how can I avoid these kind of mistakes, lets say in some for loop iterating over a std::vector:
int n = 2;
for(state_type::size_type i = 0; i < my_vec.size(); ++i) {
if(i - n >= 0)
my_vec[i - n] += 3;
}
Of course I could take i as an int, but isn't it recommended to use size_type for these kind of loops ? What is a better way to do it ? Or am I the only one who is surprised by this conversion ?
Indeed in std::vector the type
size_typeis documented as "an unsigned integral type" [...] "usually the same as std::size_t" (on my Debian/Sid/x86-64 it is a 64 bits unsigned integer). Probably passing-Walltog++would have warned you.So you better cast explicitly (perhaps to
std::ptrdiff_t), e.g. useBut in C++11 (with a recent compiler such as GCC 4.8.2) I would instead code perhaps: