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?
The Google C++ style guide recommends avoiding unsigned integers except in situations that definitely require it (for example: file formats often store sizes in uint32_t or uint64_t -- no point in wasting a signedness bit that will never be used).
An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.
A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
It takes a size of 32 bits. A maximum integer value that can be stored in an unsigned int data type is typically 4, 294, 967, 295, around 232 – 1(but is compiler dependent). The maximum value that can be stored in unsigned int is stored as a constant in the <climits> header file.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With