I'm reviewing a C++ project and see effectively the following:
std::vector<SomeType> objects;
//then later
int size = (int)objects.size();
for( int i = 0; i < size; ++i ) {
process( objects[i] );
}
Here's what I see. std::vector::size()
returns size_t
that can be of some size not related to the size of int
. Even if sizeof(int) == sizeof(size_t)
int
is signed and can't hold all possible values of size_t
. So the code above could only process the lower part of a very long vector and contains a bug. The right way would be to use size_t
for both the size
variable and the loop index.
That said I'm curious of why the author might have written this?
My only guess is that first he omitted the (int)
cast and the compiler emitted something like Visual C++ C4018 warning:
warning C4018: '<' : signed/unsigned mismatch
so the author though that the best way to avoid the compiler warning would be to simply cast the size_t
to int
thus making the compiler shut up.
Is there any other possible sane reason for that C cast?