Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I subtract an unsigned integer from a signed integer in C++?

Tags:

c++

math

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.

like image 211
Colen Avatar asked Mar 16 '11 16:03

Colen


People also ask

What happens when you subtract from an unsigned int?

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.

What happens when you cast a signed int to an unsigned int?

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).

What happens when you add signed and unsigned int?

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.


1 Answers

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.

like image 80
Steve Jessop Avatar answered Oct 20 '22 08:10

Steve Jessop