What happens if I do something like this:
unsigned int u;
int s;
...
s -= u;
What's the expected behavior of this:
1) Assuming that the unsigned integer isn't too big to fit in the signed integer?
2) Assuming that the unsigned integer would overflow the signed integer?
Thanks.
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.
If you mix signed and unsigned int, the signed int will be converted to unsigned (which means a large positive number if the signed int has a negative value).
if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
In general, consult 5/9 in the standard.
In your example, the signed value is converted to unsigned (by taking it mod UINT_MAX+1), then the subtraction is done modulo UINT_MAX+1 to give an unsigned result.
Storing this result back as a signed value to s
involves a standard integral conversion - this is in 4.7/3. If the value is in the range of signed int
then it is preserved, otherwise the value is implementation-defined. All the implementations I've ever looked at have used modulo arithmetic to push it into the range INT_MIN
to INT_MAX
, although as Krit says you might get a warning for doing this implicitly.
"Stunt" implementations that you'll probably never deal with might have different rules for unsigned->signed conversion. For example if the implementation has sign-magnitude representation of signed integers, then it's not possible to always convert by taking modulus, since there's no way to represent +/- (UNIT_MAX+1)/2
as an int.
Also relevant is 5.17/7, "The behavior of an expression of the form E1 op= E2
is equivalent to E1 = E1 op E2
except that E1
is evaluated only once". This means that in order to say that the subtraction is done in the unsigned int
type, all we need to know is that s - u
is done in unsigned int
: there's no special rule for -=
that arithmetic should be done in the type of the LHS.
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