tags:

views:

96

answers:

2

Today I made a 64bit build of my project for the first time. Basically it compiled, linked and ran ok, except for warnings complaining about incompatibility between the new, 64bit size_t type and the simple int type. This mostly occurs in situations like this in my code:

void func(std::vector<Something> &vec)
{
    int n = vec.size();
    for (int i=0; i < n; i++)
    {
        ....vec[i]....
    }
}

This is quite easy to fix, and I read an article saying one should rather use size_t or ptrdif_t as loop indices. But what can I do in a situation like this?

void outsideLibraryFunc(int n);

void func(std::vector<Something> &vec)
{
    int n = vec.size();
    outsideLibraryFunc(n);
}

I can't change the outside library's function declaration, which expects an argument of type int, and I need to pass it the number of the vector elements. What can I do other than disabling the compiler warnings?

+7  A: 

Do an explicit cast to int, e.g.

void outsideLibraryFunc(int n);

void func(std::vector<Something> &vec)
{
    outsideLibraryFunc(static_cast<int>(vec.size()));
}

It doesn't eliminate any of the potential problems with converting size_t to int, but it does tell the compiler that you're doing the conversion on purpose, and it won't warn you about it.

Tyler McHenry
+1, The greater advantage is that while reading the code you see the cast that would otherwise be implicit, and with knowledge that the compiler cannot have you can validate whether it makes sense or not. As in the example: while the compiler cannot ensure that the value returned by a function that is of type `size_t` will fit in a 32bit integer, you can manually check whether it makes sense or not.
David Rodríguez - dribeas
+2  A: 

Cast it? Seriously if you can't change the external library, there is not much you can do. To be extra safe check for overflow.

+1 for the overflow check (although you seldom have more than 2billions of objects)
Viktor Sehr
How do I check for an overflow? I do kinda recollect an overflow bit in EFLAGS, but how do I access it in a C-manner?
neuviemeporte
@neuviemeporte: if (vec.size() > INT_MAX) { /* error */} else { /* (int) cast will work */ }. But like Viktor said, the check might be overkill...
Michael Burr
Yeah the overflow check is almost definitely overkill. Just something to consider with narrowing casts. Checking the CPU's flags after the operation would not be portable. And like Michael wrote: just find or define the platform's maximum integer, compare. But really, if you have a vector with so many items it will overflow an int, you probably won't have any memory left and won't have to worry about these things.