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

前端 未结 5 889
旧时难觅i
旧时难觅i 2020-12-25 09:48

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;
 in         


        
5条回答
  •  猫巷女王i
    2020-12-25 10:35

    A cast, as Blaz Bratanic suggested:

    size_t data = 99999999;
    int convertdata = static_cast(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.)

提交回复
热议问题