When you work with unsigned types, modular arithmetic (also known as the wrap behavior) occurs. To understand this modular arithmetic, just take a look at this watch:

9 + 4 = 1 (13 mod 12), so in the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle applies when dealing with unsigned types. If the result type unsigned , then modular arithmetic takes place.
Now, consider the following operations that save the result as an unsigned int :
unsigned int five = 5, seven = 7; unsigned int a = five - seven;
If you want to make sure the result is signed , then save it in the signed variable or translate it into signed . If you want to get the difference between numbers and make sure that modular arithmetic is not applied, you should use the abs() function defined in stdlib.h :
int c = five - seven; // c = -2 int d = abs(five - seven); // d = 2
Be very careful, especially when recording conditions, because:
if (abs(five - seven) < seven) // = if (2 < 7) // ... if (five - seven < -1) // = if (-2 < -1) // ... if (one - six < 1) // = if (-5 < 1) // ... if ((int)(five - seven) < 1) // = if (-2 < 1) // ...
but
if (five - seven < 1) // = if ((unsigned int)-2 < 1) = if (4294967294 < 1) // ... if (one - six < five) // = if ((unsigned int)-5 < 5) = if (4294967291 < 5) // ...
LihO Feb 22 '13 at 17:56 2013-02-22 17:56
source share