问题
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