With an unsigned integral value unsigned int i
, a condition like i > -1
can never become true, whereas a condition i != -1
can become true. The reason is that integral literal -1
, when promoted to an unsigned value, is actually the same as MAX_UNSIGNED
. And it is then easy to see that a value of type unsigned int
can never be greater than MAX_UNSIGNED
, whereas it can happen that it is != MAX_UNSIGNED
.
Try the following code:
unsigned int ui = -1;
printf("ui:%u ; MAX_UNSINGED: %u\n", ui, UINT_MAX);
bool onegreaterMinusOne = (1 > ui);
printf("1 > -1 in unsigned realm? %s\n", (onegreaterMinusOne ? "True" : "False"));
unsigned int anotherUI = 0;
printf("0 != -1 in unsigned realm? %s\n", (anotherUI != ui) ? "True" : "False");
anotherUI--;
printf("--anotherUI != -1 in unsigned realm? %s\n", (anotherUI != ui) ? "True" : "False");
Output:
ui:4294967295 ; MAX_UNSINGED: 4294967295
1 > -1 in unsigned realm? False
0 != -1 in unsigned realm? True
--anotherUI != -1 in unsigned realm? False
A little bit subtle is the last thing, where unsigned int anotherUI=0; anotherUI--;
is evaluated (this corresponds to the last step in your first loop), because one might ask if "an unsigned underflow is defined behaviour". The answer is yes, as taken from the C++-standard (and copied from this SO answer
):
[...] 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. (ISO/IEC
9899:1999 (E) §6.2.5/9)
So (unsigned)0 - (unsigned)1
equals -1 modulo UINT_MAX+1
, or in other words, UINT_MAX
.