jeudi 29 novembre 2018

Comparison between signed and unsigned. Is static_cast the only solution?

I use third party containers that use int to store the size. I also use stl containers which use size_t to store size.

I very often in my code have to use both in the same loop, like for example:

// vec is std::vector
// list is the third party container
assert(vec.size() == list.size()); // warning
for(size_t i = 0; i < vec.size(); i++)
{
    vec[i] = list[i]; // warning
}

So to fix I have to either I do function style casting, which I was told is C style casting in disguise.

// vec is std::vector
// list is the third party container
assert(int(vec.size()) == list.size());
for(size_t i = 0; i < vec.size(); i++)
{
    vec[i] = list[int(i)]; // warning
}

Or I can do the even uglier solution that everyone recommends. The static casting.

// vec is std::vector
// list is the third party container
assert(static_cast<int>(vec.size()) == list.size());
for(size_t i = 0; i < vec.size(); i++)
{
    vec[i] = list[static_cast<int>(i)]; // warning
}

I really don't want to static_cast.

  • Can the implicit conversion in this particular scenario be dangerous?
  • Would the function style be okay in my case?
  • If static_cast is really the only safe solution. Should I cast the int to size_t or size_t to int?

Thank you.

Aucun commentaire:

Enregistrer un commentaire