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++)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With