STL Signed/Unsigned mismatch

Started by
1 comment, last by Emmanuel Deloget 18 years, 4 months ago
Say I'm trying to loop through an std::vector. I might have code like this:
for(int i=0; i<vec.size(); i++) {
...
}
Then the compiler gives me a warning about the comparison between the signed i and unsigned vec.size(). Throughout the course of my code I have about 100 of these warnings and I was wondering whether or not they had any real bearing on anything.
//------------------------------------------------------------------------------------------------------The great logician Bertrand Russell once claimed that he could prove anything if given that 1+1=1. So one day, some fool asked him, "Ok. Prove that you're the Pope." He thought for a while and proclaimed, "I am one. The Pope is one. Therefore, the Pope and I are one."
Advertisement
When just looping those warnings are usually benign, but you should consider switching to a unsigned variable anyways. Alterantely, you can use iterators to loop through the vector.
Hello !

You can write
for (std::vector<mytype>::size_type i=0; i<vec.size(); i++) {  ...}

Or (simpler, since finnaly ti will resolve to the same thing)
for (size_t i=0; i<vec.size(); i++) {  ...}

The vector<>::size() methode returns an unsigned int (it makes not sense to return a signed one).

But unless you are dealing with very large vectors (more than 231 entries), your code will work correctly.

(edit: C'mon, SiCrane, type slower please! [smile])

HTH,

This topic is closed to new replies.

Advertisement