Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kill unsigned / signed comparison error

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++)

like image 992
anon Avatar asked Dec 18 '22 01:12

anon


1 Answers

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). If you're only using i to iterate and don't need its value in the loop, use iterators instead:

for (auto iter = blahs.begin(), end = blahs.end(); iter != end; ++iter)

If your compiler does not support auto, replace auto with T::iterator or T::const_iterator, where T is the type of blahs. If your compiler supports a fuller subset of C++11, though, do this:

for (auto& element : blahs)

Which is best of all.


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 the technically correct way, assuming i will not be negative
for (int i = 0; static_cast<blah_vec::size_type>(i) < blahs.size(); ++i)
like image 178
GManNickG Avatar answered Dec 24 '22 02:12

GManNickG