Advice on unsigned int (Gangnam Style edition)

后端 未结 5 585
轻奢々
轻奢々 2021-02-02 11:38

The video \"Gangnam Style\" (I\'m sure you\'ve heard it) just exceeded 2 billion views on youtube. In fact, Google says that they never expected a video to be greater than a 32-

5条回答
  •  遥遥无期
    2021-02-02 11:51

    This guideline is extremely misleading. Blindly using int instead of unsigned int won't solve anything. That simply shifts the problems somewhere else. You absolutely must be aware of integer overflow when doing arithmetic on fixed precision integers. If your code is written in a way that it does not handle integer overflow gracefully for some given inputs, then your code is broken regardless of whether you use signed or unsigned ints. With unsigned ints you must be aware of integer underflow as well, and with doubles and floats you must be aware of many additional issues with floating point arithmetic.

    Just take this article about a bug in the standard Java binary search algorithm published by none other than Google for why you must be aware of integer overflow. In fact, that very article shows C++ code casting to unsigned int in order to guarantee correct behavior. The article also starts out by presenting a bug in Java where guess what, they don't have unsigned int. However, they still ran into a bug with integer overflow.

提交回复
热议问题