How to cast the size_t to double or int C++
If your code is prepared to deal with overflow errors, you can throw an exception if data
is too large.
size_t data = 99999999;
if ( data > INT_MAX )
{
throw std::overflow_error("data is larger than INT_MAX");
}
int convertData = static_cast<int>(data);
Static cast:
static_cast<int>(data);
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.)
You can use Boost numeric_cast
.
This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double
.
Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t
is greater than INT_MAX
. If you want to detect it use numeric_cast
or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast
to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.