Subtracting two unsigned values of the same size will result in an unsigned value. If the first operand is less than the second the result will be arithmetically in correct.
The subtraction of two n-digit unsigned numbers M - N (N * 0) in base r can be done as follows: 1. Add the minuend M to the r's complement of the subtrahend N. This performs M + (r' - N) = M - N + r'.
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.
Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges. Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive.
The following results make me really confused:
int i1 = 20-80u; // -60 int i2 = 20-80; // -60 int i3 =(20-80u)/2; // 2147483618 int i4 =(20-80)/2; // -30 int i5 =i1/2; // -30
i3
seems to be computed as (20u-80u)/2
, instead of (20-80u)/2
i3
is the same as i5
.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