How to cast the size_t to double or int C++

user2701639 picture user2701639 · Mar 4, 2014 · Viewed 120k times · Source

My question is that

I have a size_t data, but now I want to convert it to double or int.

If I do something like

 size_t data = 99999999;
 int convertdata = data;

the compiler will report warning. because it maybe overflow.

Do you have some method like the boost or some other method to do the convert?

Answer

Keith Thompson picture Keith Thompson · Mar 4, 2014

A cast, as Blaz Bratanic suggested:

size_t data = 99999999;
int convertdata = static_cast<int>(data);

is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).

But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t to int really could overflow.

If at all possible, design your program so you don't need to convert a size_t value to int. Just store it in a size_t variable (as you've already done) and use that.

Converting to double will not cause an overflow, but it could result in a loss of precision for a very large size_t value. Again, it doesn't make a lot of sense to convert a size_t to a double; you're still better off keeping the value in a size_t variable.

(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)