views:

84

answers:

1

In general, I want warnings of unsigned vs signed.

However, in this particular case, I want it suppressed;

std::vector<Blah> blahs;

for(int i = 0; i < blahs.size(); ++i) { ...

I want to kill this comparison.

Thanks!

(using g++)

+11  A: 

You should fix, not suppress. Use an unsigned type:

for (size_t i = 0; i < blahs.size(); ++i)

You can also use unsigned, but size_t is more appropriate here (and may have a different, larger, range).


Strictly speaking, the above is not "correct". It should be:

typedef std::vector<Blah> blah_vec;
blah_vec blahs;

for (blah_vec::size_type i = 0; i < blahs.size(); ++i)

But this can be verbose, and every implementation I know uses size_t as size_type anyway.


If for some reason you really need a signed integer type for i, you'll have to cast:

// assumes size() will fit in an int
for (int i = 0; i < static_cast<int>(blahs.size()); ++i)

// assumes i will not be negative (so use an unsigned type!)
for (int i = 0; static_cast<size_t>(i) < blahs.size(); ++i)

// and technically the correct way
for (int i = 0; static_cast<blah_vec::size_type>(i) < blahs.size(); ++i)
GMan