When using int
instead of std::size_t
in this code sample
std::vector<int> v {1,2,3,4};
for(int i = 0; i < v.size(); i++)
{
std::cout << v[i] << " ";
}
compiler generates following warning:
warning: comparison between signed and unsigned integer expressions
However program runs as expected and outputs:
1 2 3 4
I also notice those warnings quite often in projects I'm working on, that have been running years on production, and those warning never resulted in any problems on the side of our client. Since evidently those programs have no problem with comparing signed and unsigned integers, I would like to ask:
- is there any benefit, performance or safety-wise, to always using unsigned over signed integers where applicable?
- in what cases, if any, comparing signed and unsigned integer can result in errors or unexpected behavior?
- if there is no good reason to worry about those warnings, is there any historical reason, why this information could be useful to developers in the past?