Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid problems with size_t and int types in 64bit C++ builds?

Tags:

c++

size-t

64-bit

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?

like image 447
neuviemeporte Avatar asked Sep 30 '10 17:09

neuviemeporte


2 Answers

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.

like image 84
user318904 Avatar answered Oct 31 '22 19:10

user318904


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.

like image 21
Tyler McHenry Avatar answered Oct 31 '22 19:10

Tyler McHenry