Search code examples
c++unsigned

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


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?


Solution

  • 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