Is it safe to assign -1 to an unsigned int to get the max value?

好久不见. 提交于 2019-12-23 11:55:47

问题


Is it safe to assign -1 to an unsigned int, or other unsigned c++ data type, if I need to get the max value?

Is there any situation where it won't give me the highest value an unsigned data type can contain?


回答1:


To be on a safe side, use std::numeric_limits<unsigned int>::max(). Casting -1 to unsigned would work on mainstream platforms, but it is not guaranteed by the standard AFAIR.

UPD: I'll correct myself. (unsigned)-1 is required to be UINT_MAX in C, see the answer here




回答2:


I think you'll be okay using -1 on any 2's complement machine (which I think is everything nowadays).



来源:https://stackoverflow.com/questions/10310771/is-it-safe-to-assign-1-to-an-unsigned-int-to-get-the-max-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!