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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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