Could this C cast to avoid a signed/unsigned comparison make any sense?
Posted
by sharptooth
on Stack Overflow
See other posts from Stack Overflow
or by sharptooth
Published on 2010-04-16T12:00:31Z
Indexed on
2010/04/16
12:03 UTC
Read the original article
Hit count: 166
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.
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?
© Stack Overflow or respective owner