size_t vs int warning
Solution 1:
If you might need to hold more than INT_MAX
items in your vector, use size_t
. In most cases, it doesn't really matter, but I use size_t
just to make the warning go away.
Better yet, use iterators:
for( auto it = v.begin(); it != v.end(); ++it )
(If your compiler doesn't support C++11, use std::vector<whatever>::iterator
in place of auto
)
C++11 also makes choosing the best index type easier (in case you use the index in some computation, not just for subscripting v
):
for( decltype(v.size()) i = 0; i < v.size(); ++i )
Solution 2:
What is size_t
?size_t
corresponds to the integral data type returned by the language operator sizeof
and is defined in the header file (among others) as an unsigned integral type
.
Is it okay to cast size_t
to int
?
You could use a cast if you are sure that size is never going to be > than INT_MAX
.
If you are trying to write a portable code, it is not safe because,
size_t
in 64 bit Unix
is 64 bits
size_t
in 64 bit Windows
is 32 bits
So if you port your code from Unix to WIndows and if above are the enviornments you will lose data.
Suggested Answer
Given the caveat, the suggestion is to make i
of unsigned integral type
or even better use it as type size_t
.
Solution 3:
is this safe to ignore this warning or should I make all my loop variable of type size_t
No. You are opening yourself up to a class of integer overflow attacks. If the vector size is greater than MAX_INT
(and an attacker has a way of making that happen), your loop will run forever, causing a denial of service possibility.
Technically, std::vector::size
returns std::vector::size_type
, though.
You should use the right signedness for your loop counter variables. (Really, for most uses, you want unsigned integers rather than signed integers for loops anyway)
Solution 4:
The problem is that you're mixing two different data types. On some architectures, size_t
is a 32-bit integer, on others it's 64-bit. Your code should properly handle both.
since size()
returns a size_t
(not int), then that should be the datatype you compare it against.
std::vector v;
for ( size_t i = 0; i < v.size(); i++) {
}